views:

111

answers:

4

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;
+2  A: 
$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);
Psytronic
Sorry, syntax error, just checking now
Psytronic
This won't work, read my code again.
Click Upvote
This gives the output shown in your question
Psytronic
It does now after your edit. But i'd rather use a built in function if possible :)
Click Upvote
I don't think there is one for your specific array format. Not that I can think of off the top of my head
Psytronic
+1  A: 

Since PHP 4 you can use

array_merge  ( array $array1  [, array $array2  [, array $...  ]] )

Example:

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

The above example will output:

Array
(
    [0] => foo
    [1] => bar
)

Read more in the php manual: http://php.net/manual/en/function.array-merge.php

For multidimensional arrays (since PHP 4.0.1) you can use: array_merge_recursive ( array $array1 [, array $... ] )

Example:

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)
Sebastian
will this work with the array i gave?
Click Upvote
Nope, he didn't read the question.
e-satis
+3  A: 

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

R. Bemrose
Tested and that works. Much simpler than what I was suggesting :)
Psytronic
A: 

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.

bish