1

I would like to combine 2 arrays into 1 in PHP. I've searched this site for similar questions but can't seem to find an answer.

Array 1
(
[0] => Array
    (
        [LOGIN] => 123
        [CITY] => bangkok
        [GROUP] => bangkok-a
        [PREV_A] => 123.4
        [PREV_B] => 456.7
    )

[1] => Array
    (
        [LOGIN] => 456
        [CITY] => bangkok
        [GROUP] => bangkok-b
        [PREV_A] => 987.6
        [PREV_B] => 654.3
    )
)

Array 2
(
[0] => Array
    (
        [LOGIN] => 123
        [CITY] => bangkok
        [GROUP] => bangkok-a
        [A] => 555.5
        [B] => 666.6
    )

[1] => Array
    (
        [LOGIN] => 456
        [CITY] => bangkok
        [GROUP] => bangkok-b
        [A] => 777.7
        [B] => 888.8
    )
)

I want the resulting arrays become like this:

Array 3
(
[0] => Array
    (
        [LOGIN] => 123
        [CITY] => bangkok
        [GROUP] => bangkok-a
        [PREV_A] => 123.4
        [PREV_B] => 456.7
        [A] => 555.5
        [B] => 666.6
    )

[1] => Array
    (
        [LOGIN] => 456
        [CITY] => bangkok
        [GROUP] => bangkok-b
        [PREV_A] => 987.6
        [PREV_B] => 654.3
        [A] => 777.7
        [B] => 888.8
    )
)

Each array is 64. I've tried this code but the resulting array has 4096 (=64x64) fields and not 64.

foreach($arr1 as $x){
    foreach($arr2 as $y){
        if ($x['LOGIN']=$y['LOGIN']){
            $tmp=array();
            $tmp=array_merge($x,$y);
            array_push($res,$tmp);
        }
    }
}

How do I combine them correctly? Thank you.

1 Answer 1

2

How about:

$newArray = Array();
foreach($arr1 as $k=>$val)
{
    if(array_key_exists($k, $arr2))
    {
        $newArray[$k] = array_merge($val, $arr2[$k]);
    }
}

Haven't tested, but I think it should work...

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

1 Comment

You Sir, are amazing. That works like wonder! :D Thank you very much. +1 and answered.

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.