0

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;
1
  • Does "orange" and "apple" have the same number of items ? Commented Dec 1, 2009 at 15:26

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Tested and that works. Much simpler than what I was suggesting :)
2
$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);

2 Comments

It does now after your edit. But i'd rather use a built in function if possible :)
I don't think there is one for your specific array format. Not that I can think of off the top of my head
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.