Ali
Ali

Reputation: 267287

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'] = 10;

Upvotes: 0

Views: 258

Answers (3)

bish
bish

Reputation: 881

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.

Upvotes: 0

Powerlord
Powerlord

Reputation: 88846

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...

Upvotes: 3

Psytronic
Psytronic

Reputation: 6113

$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);

Upvotes: 2

Related Questions