set the variables that go inside array_merge_recursive - php

I need to tell array_merge_recursive what variables it needs to merge
I have the variable names that I need to use as strings, for example I have the following
$array1 = array('color'=>'blue', 'taste'=> 'sour', 'size'=>'big');
$array2 = array('color'=>'green', 'taste'=> 'sweet', 'size'=>'medium');
$array3 = array('color'=>'black', 'taste'=> 'sour', 'size'=>'small');
$array4 = array('color'=>'grey', 'taste'=> 'sweet', 'size'=>'big');
$allarrays = array_merge_recursive($array1, $array2, $array3, $array4);
This will work okay and merge my arrays, but I need to add a foreach to get the list of the arrays that I need and to set the array's that are going to the merged.
$arraysThatINeedToAddToTheMerge = array('array2', 'array4');
foreach ($arraysThatINeedToAddToTheMerge as $data){
$toBeMerged[] = $data;
}
$allarrays = array_merge_recursive($toBeMerged);
This doesn't work as it looks like I cannot use an array as the arguments for the array_merge_recursive.
I was thinking maybe I can use the list function for this but I haven't used it yet, what can I use to get what I need?

Two elements to handling this the way you want to:
Variable variables to build the to be merged array
$arraysThatINeedToAddToTheMerge = array('array2', 'array4');
$toBeMerged = [];
foreach ($arraysThatINeedToAddToTheMerge as $data){
$toBeMerged[] = $$data;
}
This will build an array of arrays, rather than simply an array of the names of your variables;
And (a modern PHP solution) then unpack the array arguments to be merged when calling array_merge_recursive
$allarrays = array_merge_recursive(...$toBeMerged);
or use call_user_func_array() for older versions of PHP
$allarrays = call_user_func_array('array_merge_recursive', $toBeMerged);

Related

clone array and add a subarray

i have the following problem. i have a large array structure which i assign values from a sql statement:
$data[$user][$month]['id'] = $data->id;
$data[$user][$month]['company'] = $data->company;
...
...
and around 30 other values.
i need to clone this array ($data) and add a subarray like:
$data[$user][$month][$newsubarray]['id'] = $data->id;
$data[$user][$month][$newsubarray]['company'] = $data->company;
...
...
i need to clone it because the original array is used by many templates to display data.
is there a way to clone the array and add the subarray without assign all the values to the cloned array? this blows up my code and is very newbi, but works.
You can use array_map, check the live demo
if you want to pass parameter to array_map(), use this
array_map(function($v) use($para1, $para2, ...){...}, $array);
Here is the code,
<?php
$array =array('user'=> array('month'=>array('id' =>2, 'company' => 3)));
print_r($array);
print_r(array_map(function($v){
$arr = $v['month'];
$v['month'] = [];
$v['month']['newsubarray'] = $arr;
return $v;}
, $array));
You can iterate through the array with nested foreach loops.
It would look similar to this:
foreach ($data as $user=>$arr2) {
foreach ($arr2 as $month=>$arr3) {
foreach ($arr3 as $key=>$value) {
$data[$user][$month][$newsubarray][$key] = $value;
}
}
}
Your last level of array, you can create object, for holding data with implementing ArrayAccess. Then simply by reference, assign object in desire places. This way, you can hold 1 object and use it multi places, but if you change in one - this change in all.
Then you addictionaly, can implements __clone method to clone object correctly.

$array["key"] = value; or array_merge(), which is the fastest way?

Which is the best (performance efficiency) way to create an array in multiple files?
This:
$arr = array();
$arr["key1"] = "val1";
$arr["key2"] = "val2";
include "arr_2.php";
arr_2.php:
$arr["key3"] = "val3";
$arr["key4"] = "val4";
Or this:
$arr = array("key1"=>"val1", "key2"=>"val2");
include "arr_2.php";
arr_2.php:
$arr = array_merge($arr, array("key3"=>"val3", "key4"=>"val4"));
ARRAY KEY => VALUE is faster than ARRAY_MERGE.
KEY VALUE is a simple creation of ARRAY ELEMENTS similar to creating a simple variable and assigning a value to it.
ARRAY_MERGE will always take previous array and merge values all over again, which involves more processing.
You will notice significant performance impact when run in a loop.
Hope this helps!

PHP - Variable Variables & array_merge() - not working

I have a bunch of arrays, which are stored in different variables like $required, $reserved, etc...
I would like to allow (inside a function) an array of options to be passed (like $options = array('required', 'reserved')), and that array would then be used to define which arrays to merge together and return at the end of the function.
So, I have this code in part of the function, that should grab all the options and merge the arrays, using variable variables to get the arrays from the strings passed in the options array):
$array = array();
foreach ($options as $key) {
$array_to_merge = ${$key};
array_merge($array, $array_to_merge);
}
return $array;
However, when I return the $array, it shows 0 items. If I print_r($array_to_merge);, I actually get the entire array as I should.
Does array_merge() simply not work with variable variables, or am I missing something here...?
array_merge returns the merged array, you're not assigning that return value to anything and thus it is being lost.
$array = array_merge($array, $array_to_merge);
should fix your problem.
If I read it right you can also simplify your code (replaces the loop) to just:
$array = call_user_func_array("array_merge", compact($options));
compact replaces the variable variable lookup and gets the list of arrays. And in effect there is only one array_merge call necessary.

PHP Array Combination Best Method

given the following arrays in php, how can i best merge them together
$masterkeys = array('Key1','Key2');
$settings_foo = array(
array('ID'=>'Key1',
'Foo_Setting'=>'SomeValue'));
$settings_bar = array(
array('ID'=>'Key1',
'Bar_Setting'=>'SomeOtherValue'));
in the end I need $masterkeys to be the combination of each of the settings_[foo|bar] arrays.
Array( ['Key1'] = Array('Foo_Setting'=>'SomeValue','Bar_Setting'=>'SomeOtherValue') );
I do know I can use a couple foreach loops on this, but just wondering if there are a couple PHP array functions that can splice them together.
While you can use some of PHP's array functions, your input data isn't in a very nice format. You'll have the fewest iterations (and probably best performance) by writing them yourself:
# create an array of $masterkey => array()
$result = array_combine($masterkeys, array_fill(0, count($masterkeys), array()));
# loop through each settings array
foreach (array($settings_foo, $settings_bar) as $settings)
{
foreach ($settings as $s)
{
# merge the array only if the ID is in the master list
$key = $s['ID'];
if (array_key_exists($key, $result))
$result[$key] = array_merge($result[$key], $s);
}
}
# unset all extraneous 'ID' properties
foreach (array_keys($result) as $i)
unset($result[$i]['ID']);
var_dump($result);
As an alternative, you could look into array_map and array_filter, but due to the way the data is structured, I'm not sure they'll be of much use.
I'm not sure how your $masterkeys array plays in here, but array_merge_recursive may do what you want.

merging two set of array values into one multidimesional array

i'm a newbie in programming and in php too and i was wondering if anyone can help me with my array problem.
i have two set of array, example:
$name = array("peter","peter","joe");
$cars = array("ford", "gmc", "mercy");
and i would like to merge them into a multidimensional array like this
$merge = array(array($name[0], $cars[0]),array($name[1], $cars[1]),array($name[2], $cars[2]));
now, i would like keep the structure as above but i would like to do it with a native array function or foreach function.
i've tried array_merge and array_combine but it didn't turn out as i expected.
i've tried $arr3 = $name + $cars; but it didn't work too
does anyone can help me on what function should i use?
many thanks
~aji
array_map sounds like what you are looking for. See "Example #4 Creating an array of arrays"
An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function
$merged = array_map(NULL, $name, $cars);
$name = array("peter","peter","joe");
$cars = array("ford", 'gm$c', "mercy");
for($i=0;$i<count($name);$i++){
$array[$i]=array($name[$i],$cars[$i]);
}
print_r($array);

Categories