How to merge this two specific arrays in PHP?
I have this array:
$array['apples'][0]['name'] = 'Some apple';
$array['apples'][0]['price'] = 44;
$array['oranges'][0]['name'] = 'Some orange';
$array['oranges'][0]['price'] = 10;
How can I merge the two arrays so i get this:
$array[0]['name'] = 'Some apple';
$array[0]['price'] = 44;
$array[1]['name'] = 'Some orange';
$array[1]['price'] =开发者_Python百科 10;
I don't have PHP here to test, but isn't it just:
$array2 = $array['apples'];
array_merge($array2, $array['oranges']);
Granted, this is now in $array2
rather than $array
...
$second_array = array(); foreach($array as $fruit => $arr){ foreach($arr as $a){ $second_array[] = array("name" => $a["name"], "price" => $a["price"]); } } print_r($second_array);
It looks like the values of $array
are the arrays that you want to merge. Since this requires a dynamic number of arguments passed to array_merge, the only way I know to accomplish it is through call_user_func_array
:
$array = call_user_func_array('array_merge', array_values($array));
That should work with any amount of fruit.
精彩评论