Jump to content

Merging arrays question


OsvaldoM

Recommended Posts

Hello,

i've been reading the php manual and googling around with no luck so far.

Basically what i want to do is to merge two arrays the following way:

 

$array1 = array("dog" => "brown",
"cat" => "white");

$array2 = array("dog" => "black",
"duck" => "white") ;

 

and have this as a result:

 

$array3 = array("dog" => array("brown",  "black"),
"cat" => "white",
"duck" => "white") ;

 

I know it's possible and probably quite simple, but my tests so far have failed miserable, basically i get stuck trying to push "black" into the array, whenever "dog" is repeated.

Any pointers or suggestions would be quite appreciated!

Link to comment
https://forums.phpfreaks.com/topic/198440-merging-arrays-question/
Share on other sites

A simple work around would be.

<?php

$array1 = array("dog" => "brown",
"cat" => "white");

$array2 = array("dog" => "black",
"duck" => "white") ;

foreach($array1 as $key => $value) {
$array3[$key][] = $value;
}

foreach($array2 as $key => $value) {
$array3[$key][] = $value;
}

echo '<pre>';
print_r($array3);
echo '</pre>';
?>

you guys rock, thanks for this... somehow i skipped the array_merge_recursive function in the manual.

As i've been dealing with a lot of arrays lately, i've noticed that foreach is not the best way to deal with large arrays, built-in php functions for arrays should be the way to go, sadly, im still not that familiar with all of them...

@OsvaldoM

If you want to work with each item or each nested array foreach or while>each ~is~ the best way. But both are inefficient if you want to find one item or see if the array contains something, then array_search or array_key_exists is the way to go.

 

 

HTH

Teamatomic

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.