How to enclose an array in a conditional if? - arrays

For example, I have the following code:
<?php
$options = array(
array(
"type" => "section",
"icon" => "acera-icon-preference",
"title" => "General Settings",
"id" => "general",
"expanded" => "true"
),
array(
"under_section" => "ajax_login",
"type" => "checkbox",
"name" => "Who's Online Options",
"id" => array("tigu_whosonline_list", "tigu_whosonline_avatar"),
"display_checkbox_id" => "tigu_show_whosonline",
"img_desc" => "",
"options" => array("Who's Online List", "Who's Online Avatars"),
"desc" => "",
"default" => array("checked", "checked")
) );
?>
There a more arrays but I shortened the code to save space. The question is:
How can I include only the following code
array(
"type" => "section",
"icon" => "acera-icon-preference",
"title" => "General Settings",
"id" => "general",
"expanded" => "true"
),
in a conditional if somethink like this code (that get errors):
if(function_exists('bp_is_active') ):
array(
"type" => "section",
"icon" => "acera-icon-preference",
"title" => "General Settings",
"id" => "general",
"expanded" => "true"
),
endif;
The function bp_is_active it check if BuddyPress plugin is instaled. I need that code to be displayed on my wp admin panel only if BuddyPress plugin is instaled.
Thanks!

You could use the ?: ternary conditional operator:
$options = array(
function_exists('bp_is_active') // condition
? array(...stuff...) // if true
: array(), // if false
...more arrays...
);
That will use an empty array if the condition is false. If you want nothing there (as opposed to array()), you'll need something more complex.

I think you just need semicolon (;), following code is valid:
if(function_exists('bp_is_active') ):
array(
"type" => "section",
"icon" => "acera-icon-preference",
"title" => "General Settings",
"id" => "general",
"expanded" => "true"
); // <<--here
endif;
or without endif:
if(function_exists('bp_is_active') ){
array(
"type" => "section",
"icon" => "acera-icon-preference",
"title" => "General Settings",
"id" => "general",
"expanded" => "true"
); // <<--here
}

Related

Nested array validation rules not working on update in laravel

I have an array like this
"fio" => "John Dou"
"city" => "1"
"birthday" => "2022-10-21"
"email" => "test#gmail.ru"
"phones" => array:2 [▼
0 => array:2 [▼
"id" => "7"
"number" => "911"
]
1 => array:2 [▼
"id" => "10"
"number" => "112"
]
]
The check for uniqueness works, but when you try to update the current record, it swears for duplication
public function rules()
{
return [
'phones.*.number' => 'required|string|max:12|unique:'.Phone::class.',number,phones.*.id';
]
}
Maybe I made a mistake somewhere?

How would I write a WordPress function to run a json_encode and file_put_contents whenever a specific CPT post is saved

I need to generate a custom JSON file from custom fields in a custom post type. But I'm not sure what the proper function is for accomplishing this, or if my syntax is anywhere close to correct in the first place. I haven't worked much with JSON, and have never attempted to create one from dynamic content before.
I'm using an example json file for the mapping plugin I'm using as my model, but I suspect that I'm not writing the array in the right format by using this other JSON file.
In any case, embarrassingly, here's what I've got so far (and it's definitely not working):
function wpdocs_retailers_json($post_id) {
$maplocations = Array( ?>
{
"mapwidth": "1000",
"mapheight": "500",
"categories": [ {
"id": "food",
"title": "Fast-foods & Restaurants",
"color": "#a5a5a2",
"show": "false"
},
{
"id": "dep",
"title": "Department Stores",
"color": "#a5a5a2",
"show": "true"
},
{
"id": "clothing",
"title": "Clothing & Accessories",
"color": "#a5a5a2",
"show": "true"
},
{
"id": "health",
"title": "Health & Cosmetics",
"color": "#a5a5a2",
"show": "true"
},
{
"id": "misc",
"title": "Miscellaneous",
"color": "#a5a5a2",
"show": "true"
} ],
<?php if(have_rows('mall_levels', 'option')) { ?>
"levels": [ {
<?php while(have_rows('mall_levels', 'option')) {
the_row();
$level_svg = get_sub_field('svg_mall_level');
$level = get_sub_field('what_level_is_this');
?>
"id": "<?php echo esc_html($level->slug); ?>",
"title": "<?php echo esc_html($level->name); ?>",
"map": "<?php echo $level_svg; ?>",
<?php $locargs = array(
'post_type' => 'retailers',
'post_status' => 'publish',
'posts_per_page' => 0,
'orderby' => 'title',
'order' => 'ASC'
);
$locloop = new WP_Query($locargs);
if($locloop->have_posts()) { ?>
"locations": [
<?php while($locloop->have_posts()) {
$locloop->the_post();
$space = get_field('space_id'); ?>
{
"id": "space-<?php echo $space; ?>",
"title": "<?php the_title(); ?>",
"about": "Lorem ipsum",
"description": "<?php the_content(); ?>",
<?php $cats = get_the_terms($post->ID, 'dir_cats');
$catsCount = count($cats);
if($catsCount = 0) { ?>
"category": "<?php echo $cat->name; ?>"
<?php }
if($catsCount > 0) { ?>
"category": [<?php echo '"' . __($cat->name) . '"'; ?>]
<?php } ?>
"link": "<?php the_permalink(); ?>",
"x": "0.3721",
"y": "0.4296"
},
<?php } //endwhile; ?>
]
<?php } //endif;
} //endwhile; ?>
},
]
<?php } //endif; ?>
}
<?php );
$json = json_encode($maplocations);
$bytes = file_put_contents('mall.json', $json);
}
add_action('save_post_retailers', 'wpdocs_retailers_json');
I think, at least in part, the array needs to be written more like this? But I'm not sure:
"mapwidth" => "1000",
"mapheight" =>"500",
"categories" => Array(
array(
"id" => "food",
"title" => "Fast-foods & Restaurants",
"color" => "#a5a5a2",
"show" =>"false"
),
array(
"id" => "dep",
"title" => "Department Stores",
"color" => "#a5a5a2",
"show" => "true"
),
...etc.
Thanks in advance for any guidance you can provide. I apologize for my utter lack of knowledge to begin with on this one. Please be kind.
(...) the array needs to be written more like this?
Yes, you want to use that array syntax to make your life easier in the long run (IMO at least).
Here are some changes to your code. Untested though so let me know how it goes and/or if you have any further comments/questions.
function wpdocs_retailers_json($post_id) {
$maplocations = array(
"mapwidth" => 1000,
"mapheight" => 500,
"categories" => array(
array(
"id" => "food",
"title" => "Fast-foods & Restaurants",
"color" => "#a5a5a2",
"show" => "false"
),
array(
"id" => "dep",
"title" => "Department Stores",
"color" => "#a5a5a2",
"show" => "false"
),
array(
"id" => "clothing",
"title" => "Clothing & Accessories",
"color" => "#a5a5a2",
"show" => "false"
),
array(
"id" => "health",
"title" => "Health & Cosmetics",
"color" => "#a5a5a2",
"show" => "false"
),
array(
"id" => "misc",
"title" => "Miscellaneous",
"color" => "#a5a5a2",
"show" => "false"
)
)
);
// We have map levels, save them to
// our json file
if(have_rows('mall_levels', 'option')) {
$maplocations['levels'] = array();
while(have_rows('mall_levels', 'option')) {
the_row();
$level_svg = get_sub_field('svg_mall_level');
$level = get_sub_field('what_level_is_this');
$level_data = array(
"id" => esc_html($level->slug),
"title" => esc_html($level->name),
"map" => $level_svg,
)
$locargs = array(
'post_type' => 'retailers',
'post_status' => 'publish',
'posts_per_page' => 0,
'orderby' => 'title',
'order' => 'ASC'
);
$locloop = new WP_Query($locargs);
// We have some locations, save them as well
if($locloop->have_posts()) {
$level_data['locations'] = array();
while($locloop->have_posts()) {
$locloop->the_post();
$space = get_field('space_id');
$title = get_the_title();
$content = get_the_content();
$cats = get_the_terms(get_the_ID(), 'dir_cats');
$permalink = get_permalink();
$level_data['locations']['id'] = 'space-' . esc_attr($space);
$level_data['locations']['title'] = esc_html($title);
$level_data['locations']['about'] = 'Lorem Ipsum';
$level_data['locations']['description'] = $content;
if ( count($cats) ) {
$level_data['category'] = join(', ', wp_list_pluck($cats, 'name'));
}
$level_data['locations']['link'] = esc_url( $permalink );
$level_data['locations']['x'] = '0.3721';
$level_data['locations']['y'] = '0.4296';
}
// Restore original post data
wp_reset_postdata();
}
// Add our $level_data array to $maplocations
$maplocations['levels'][] = $level_data;
}
}
// Convert PHP array into JSON string
$json = json_encode($maplocations);
// Save json string to mall.json
$bytes = file_put_contents('mall.json', $json);
}
add_action('save_post_retailers', 'wpdocs_retailers_json');
Note that file_put_contents('mall.json', $json); probably should use a full path to the folder where you want to store your mall.json file.
#cabrerahector Got me super close. After a little more trial and error, the last part of the above needs to go like this:
$mapjson = json_encode($maplocations);
$j_dir = get_stylesheet_directory();
$mapdata = '/json/mall.json';
file_put_contents($j_dir . $mapdata, $mapjson, LOCK_EX);
update_post_meta($post_id, 'mall, $date);
}
add_action('save_post_retailers', 'retailers_map_json', 20);
(note, I did change the name of the function to "retailers_map_json" instead of "wpdocs_retailers_json".

How can I use array_replace inside foreach loop?

colums_arr:
array:4 [▼
0 => "id"
1 => "name"
2 => "productgroup"
3 => "category"
]
fields:
{#9767 ▼
+"id": array:9 [▶]
+"name": array:8 [▼
"fieldName" => "name"
]
+"productgroup": array:19 [▼
"fieldName" => "productgroup"
"mappedBy" => null
]
+"category": array:19 [▼
"fieldName" => "category"
"mappedBy" => null
]
}
What I want to do is, whenever in fields mappedBy exists for the element, I want to add name to the value. So as a result columns_arr should look like this:
array:4 [▼
0 => "id"
1 => "name"
2 => "productgroup.name"
3 => "category.name"
]
This is my approach:
foreach ($fields as $field) {
$MappedBy = isset($field['mappedBy']);
if($MappedBy != true){
$class_field = $field['fieldName'];
$key = array_search($field['fieldName'],$input);
$replace=array($key=>$class_field.".name");
$columns_arr = (array_replace($input,$replace));
}
}
The problem is, that my result is now:
array:4 [▼
0 => "id"
1 => "name"
2 => "productgroup"
3 => "category.name"
]
Why is name not added to productgroup?
I couldn't really answer your question, it's a bit unclear what you're doing and where your values are coming from etc. so I tried to rebuild your arrays and this is what I got without using array_search:
<?php
$columns = array(0 => "id", 1 => "name", 2 => "productgroup", 3 => "category");
$fields = array("id" => 9, "name" => array("fieldName" => "name"), "productgroup" => array("fieldName" => "productgroup", "mappedBy" => null), "category" => array("fieldname" => "category", "mappedBy" => null));
foreach ($fields as $key => $field) {
if($key !== "id" && $key !== "name"){
if(!isset($field['mappedBy'])){
foreach($columns as $ckey => $column){
if($column === $key){
$columns[$ckey] = $column.".name";
}
}
}
}
}
var_dump($columns);
var_dump outputs:
array(4) { [0]=> string(2) "id" [1]=> string(4) "name" [2]=> string(17) "productgroup.name" [3]=> string(13) "category.name" }
foreach ($fields as $key => $field) {
$MappedBy = isset($field['mappedBy']);
if($MappedBy != true){
$columns_arr[$key] = $field['fieldName'].".name";
}
}
You need to overwrite the correct key of your array like this.

Sort array by string value with special sorting if value starts with number

This is an example array
$values[0] = array("id" => "1",
"name" => "100mA");
$values[1] = array("id" => "2",
"name" => "0.1mA");
$values[2] = array ("id" => "3",
"name" => "500mA");
$values[3] = array ("id" => "4",
"name" => "1000mA");
$values[4] = array ("id" => "5",
"name" => "1000V");
$values[5] = array( "id" => "6",
"name" => "500V");
$values[6] = array("id" => "7",
"name" => "0.5mA");
$values[7] = array( "id" => "8",
"name" => "10mA");
$values[8] = array( "id" => "9",
"name" => "TO-220");
$values[9] = array( "id" => "10",
"name" => "TO-92");
$values[10] = array( "id" => "11",
"name" => "white");
$values[11] = array( "id" => "12",
"name" => "black");
I want to sort it by "name". The problem is that name is a string. The String could consist of chars but also of numbers and chars.
If "name" is a combination i want to sort it by the leading numbers.
I dont know how to to that.
Any ideas?
You can try to convert the strings letter in ASCI-Code and sort them. Not sure if you would be happy with the result but try it.

How do I access request arrays within arrays

I have the following request;
Collection {#278
#items: array:3 [
0 => array:2 [
0 => array:8 [
"id" => 631
"name" => "OIL, FILTER O.E.M."
"partno" => "235-00"
"oemnumber" => "16099 003"
"stock" => 0
"price" => "30"
"qty" => 1
"total" => 30
]
1 => array:8 [
"id" => 23
"name" => "SPEEDOMETER"
"partno" => "122-"
"oemnumber" => "25005 1013"
"stock" => 0
"price" => "276"
"qty" => 1
"total" => 276
]
]
1 => array:2 [
0 => array:2 [
"description" => "Oil change"
"hours" => "1"
]
1 => array:2 [
"description" => "Tune up"
"hours" => "2"
]
]
2 => array:15 [
"id" => 1
"custId" => 9046
"bikeId" => 5238
"trans" => "yes"
"transDetails" => "call cab"
"policies" => "Yes"
"locker" => "1"
"lockerContents" => "stuff"
"estimate" => "Yes"
"oldparts" => "Yes"
"status" => "Pending"
"created_by" => null
"created_at" => "2016-05-19 14:40:59"
"updated_by" => null
"updated_at" => "2016-06-08 09:06:58"
]
]
}
I am getting this through;
$collection = collect($request->all());
How should I go about accessing the attributes in these arrays? I have tried pluck with no joy. I suspect I could do a loop over them but with no array_expression for the arrays do I need to use the index?

Resources