Lois
Lois

Reputation: 5

How to merge Arrays having same keys only and neglect different keys?

I am new in PHP and love to learn it. I want to merge two or more arrays having same keys only. And neglect the arrays whose keys are not in both the Arrays. Like

Here is the First Array :

Array
(
[1] => Array
    (
        [111] => 36265
    )

[2] => Array
    (
        [222] => 36265
    )

[3] => Array
    (
        [333] => 36265
    )
)

and Second Array as :

Array
(
[1] => Array
    (
        [444] => 36265
    )

[2] => Array
    (
        [555] => 36265
    )

[4] => Array
    (
        [666] => 36265
    )
)

And i want my result to be as :

Array
(
[1] => Array
    (
        [111] => 36265
        [444] => 36265
    )

[2] => Array
    (
        [222] => 36265
        [555] => 36265
    )

)

Neglecting the rest Array with key [3] & [4]....

So Please anyone tell me how to get this. I try out "array_merge_recursive()" but this one displays all keys. Thanks in advance.

Upvotes: 0

Views: 191

Answers (3)

billyonecan
billyonecan

Reputation: 20270

You'd have to loop over one of the arrays, check for the existence of the current key in the other array, if it exists, merge them, eg:

$output = array();
foreach ($array1 as $key => $value) {
  if (array_key_exists($key, $array2)) {
    $output[$key] = $value + $array2[$key];
  } 
}

Here's a demo

Upvotes: 1

user1978142
user1978142

Reputation: 7948

You could also use a foreacah loop and create a new one. While in this loop you can use one of the arrays keys to match them both. Consider this example:

 $array1 = array( 1 => array(111 => 36265), 2 => array(222 => 36265), 3 => array(333 => 36265), ); $array2 = array( 1 => array(444 => 36265), 2 => array(555 => 36265), 4 => array(666 => 36265), );

$new_array = array();
foreach($array1 as $key => $value) {
    if(isset($array2[$key])) {
        $new_array[$key][key($array1[$key])] = reset($array1[$key]);
        $new_array[$key][key($array2[$key])] = reset($array2[$key]);
    }
}

echo '<pre>';
print_r($new_array);
echo '</pre>';

Should yield something like this:

Array
(
    [1] => Array
        (
            [111] => 36265
            [444] => 36265
        )

    [2] => Array
        (
            [222] => 36265
            [555] => 36265
        )

)

Upvotes: 0

Brent Baisley
Brent Baisley

Reputation: 12721

You're probably looking for array_intersect_key.

Upvotes: 0

Related Questions