Add generated arrays to another array - php

I have a array (generated by a function) that contains arrays and I want to add them to another array.
foreach ($elements as $element) {
$array[] =
array(
'name' => 'name_'.$element->name,
'desc' => 'Stuff for for '.$element->desc,
'attributes' => array(),
'type' => 'textarea'
);
}
And I have this:
$settings['var'] = array(
array(
array(
'name' => 'Test 1',
'desc' => 'This is test 1',
'attributes' => array(),
'type' => 'textarea'
),
array(
'name' => 'Test 2',
'desc' => 'This is test 2',
'attributes' => array(),
'type' => 'textarea'
),
),
);
Now I want to add all the elements in the first array (array[]) into the settings array.
If I do it like:
$settings['var'] = array(
array(
array(
'name' => 'Test 1',
'desc' => 'This is test 1',
'attributes' => array(),
'type' => 'textarea'
),
$array[0],
$array[1]...
it works, but I want to add all arrays in $array[] to the array.
I can't use a foreach here, so how can I do that?

To get the result you want, you can use array_merge inside the array:
$settings['var'] = array( array_merge(array1, array2))
the elements of array1 and array2 are arrays in your case.
Please refer to documentation for more details.

Related

PHP if statement inside an array

I'm trying to write the below array if a value is set. How can I do this inside of an array? I know I could use a ternary operator but i'm not sure how.
array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
if($Value === 1){
//Need to write the below when value is true
array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
),
}
),
You cannot intersect a definition of an array with a conditional statement. What you need to do instead is to define your array first and then do an if statement which will add to the array. It's not entirely clear at what level of your array you want to add the conditional content, so I'll show it on a simplified example:
$value = 1;
$myArray = array(
'name' => 'Joe',
'kids' => array(
'name' => 'Mary',
),
);
if ($value === 1) {
$myArray['kids']['hobbies'] = 'kite flying';
}
After this, the variable $myArray will have the following content:
array(
'name' => 'Joe',
'kids' => array(
'name' => 'Mary',
'hobbies' => 'kite flying',
),
)
Where exactly you need to put your conditional data depends on the full structure of your array, but the idea is you access the parts you want through indices.
Edit: in case you can just add the needed subarray at the end of your array, you can utilize array_push.
There is 3 variants to do this:
// Variant 1
// Anonymous function, variables from the parent scope
$Value = 1;
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => function() use ($Value) {
if ($Value == 1)
return array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
);
}
);
print_r($arr['ifArray']());
// Variant 2
// Anonymous function, variable assignment
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => function($Value) {
if ($Value == 1)
return array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
);
}
);
$Value = 1;
print_r($arr['ifArray']($Value));
// Variant 3
// Ternar operator
$Value = 1;
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => $Value != 1 ? null : array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
)
)
);
print_r($arr['ifArray']);
However, the variant that El_Vanja suggested, might be more clear than those three.

Recursive replace one array with specific key with another arrays

I have an array where all arrays where key type == 'foo' must be replaced by a custom arrays.
Basically I need to find a specific array and then replace it with other arrays.
The issue here you can easily replace one array but when you insert numbers of arrays you are shifting keys so the next array type == 'foo' will not be replaced
Any help would be appreciated.
Here's what I have:
$array = array(
array(
'options' => array(
array(
'type' => 'foo'
),
array(
'type' => 'foo'
),
array(
'type' => 'bar'
)
)
),
array(
'options' => array(
array(
'type' => 'bar'
),
array(
'type' => 'bar'
),
array(
'type' => 'foo'
)
)
),
);
And I have an array which should replace any array where type == 'foo'
$array_foo = array(
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
);
Here is the desired output:
$array = array(
array(
'options' => array(
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
array(
'type' => 'bar'
)
)
),
array(
'options' => array(
array(
'type' => 'bar'
),
array(
'type' => 'bar'
),
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
)
),
);
Thank you.
Here's a way using 2 nested foreach loops and array_merge() with a temporary array:
// Pass the array by reference
foreach ($array as &$sub) {
// Temporary array
$new_options = [];
// Loop through options
foreach ($sub['options'] as $opt) {
// if type foo: replace by $array_foo items
if ($opt['type'] == 'foo') {
$new_options = array_merge($new_options, $array_foo);
// else, keep original item
} else {
$new_options[] = $opt;
}
}
// replace the options
$sub['options'] = $new_options;
}
And check the output:
echo '<pre>' . print_r($array, true) . '</pre>';
See also Passing by Reference
According to a previous post, the code for changing could be done in a similar fashion to the following code:
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
So with your method instead of having numbers or indexes, I think you might be able to get away with writing down foo instead to get the replacement to work properly.
The other thing you might look into is array merge-recursive which can be found at: http://php.net/array_merge_recursive
The problem you stated here looks similar to this post: PHP Array Merge two Arrays on same key
I hope this helps you.

How to walk down array tree adding new keys to same level?

Firs off, I am struggling to phrase the questions correctly... so bear with me. I am trying to modify the given array using a foreach loop that runs through each array key/value recursively. However, I do not want to replace a key or value, instead I need to add a new key and value to the same level as the matched key.
In the code below I walk through each key value in the array, and if a key and value match, I want to add a new key to that same level where the match occurred. I can find the match, but I don't know how to update the array. I would rather update the existing array than build a new one.
Here's what I am trying to accomplish
Given this array:
array(
array(
'name' => 'name',
'label' => 'Label'
),
array(
'name' => 'name',
'label' => 'Label',
'sub_fields' => array(
array(
'name' => 'my_desired_target',
'label' => 'Label'
)
)
)
);
function change_recursively($arr){
foreach($arr as $key => $val){
if(is_array($val)){
change_recursively($val);
}else{
if($key == 'name' && $val == 'my_desired_target'){
//How to add new key here?
$arr['new_key'] = 'my new value';
}
}
}
}
Below is the result I am looking for if I were to var_dump $arr. In this case the key 'name' and the value 'my_desired_target" were matched, and a new key 'new_key' and value 'my new value' were added to that same level.
array(
array(
'name' => 'name',
'label' => 'Label'
),
array(
'name' => 'name',
'label' => 'Label',
'sub_fields' => array(
array(
'name' => 'my_desired_target',
'label' => 'Label',
'new_key' => 'my new value'
)
)
)
)
I have looked into using array_walk_recursive, and array_map, but neither function seems to track how deep you are in the array.
Use references:
Helpful link: PHP foreach change original array values
Your working code:
$arr = array(
array(
'name' => 'name',
'label' => 'Label'
),
array(
'name' => 'name',
'label' => 'Label',
'sub_fields' => array(
array(
'name' => 'my_desired_target',
'label' => 'Label'
)
)
)
);
function change_recursively(&$arr){
foreach($arr as $key => &$val){
if(is_array($val)){
change_recursively($val);
}else{
if($key == 'name' && $val == 'my_desired_target'){
//How to add new key here?
$arr['new_key'] = 'my new value';
}
}
}
}
change_recursively($arr);
print_r($arr);
Hope it helps!

passing arrays to taxonomy metabox

Good evening... I would like to pass array values as options to an array key (options).
This is what I would like to achieve:
array(
'name' => 'Select',
'id' => 'select',
'type' => 'select',
'options' => array( // Array of value => label pairs for radio options
'value1' => 'Label 1',
'value2' => 'Label 2'
),
),
Can't seem to pass a variable as options values. Example
$myarray = array('value1' => 'Label 1', 'value2' => 'Label 2')
array(
'name' => 'Select',
'id' => 'select',
'type' => 'select',
'options' => $myarray
),
The plugin I am working with is Taxonomy Meta from http://www.deluxeblogtips.com/taxonomy-meta-script-for-wordpress. Thanks in advance
You need to use proper PHP syntax and it will work just fine. Try this
<?php
$myarray = array('value1' => 'Label 1', 'value2' => 'Label 2');
$arr = array(
'name' => 'Select',
'id' => 'select',
'type' => 'select',
'options' => $myarray
);
print_r($arr);
I have a solution for it. I wasn't doing anything wrong except that I created the variable outside the function that created the array.
All I did was to create the variable inside the function that created the array and it worked. Thanks #RiggsFolly.

Put new data to specific keys in array PHP

I want to add some data to an existing array without modifying any of the existing keys or values.
The original array is like this:
array(
'sections' => array(
array(
'id' => 'sections_id',
'title' => 'sections_title'
)
),
'settings' => array(
array(
'id' => 'settings_id',
'title' => 'settings_title'
)
)
);
Now I want to be ablle to add new arrays to sections key and to settings key that will turn the following into :
array(
'sections' => array(
array(
'id' => 'sections_id',
'title' => 'sections_title'
),
array(
'id' => 'NEW_sections_id',
'title' => 'NEW_sections_title'
)
),
'settings' => array(
array(
'id' => 'settings_id',
'title' => 'settings_title'
),
array(
'id' => 'NEW_settings_id',
'title' => 'NEW_settings_title'
)
)
);
I tried using array_push and array_merge without success I hope someone can help.
Thank you!
you would do it just like you would any other array.
$array['sections'][] = array('id' => 'sec_id', 'title' => 'sec_title');

Categories