Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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