phparraysassociative-arraymerging-data

Append data from one subarray to another subarray


I have some issue to re-arrange array in php.

Array
(
    [N] => Array
        (
            [68] => sssssss ttttttt
            [69] => uuuuuu vvvvvvvv
        )

    [D] => Array
        (
            [05] => zzzzzzzz zzzzzzzz
            [07] => tttttttttttt ttttttttttt
        )

    [P] => Array
        (
            [88] => yyyyyyy zzzzzzzz
        )

    [C] => Array
        (
            [04] => wwwwww wwwwwww
            [06] => iiiiiii iiiiiiii
            [41] => zzzzzzzzzz zzzzzzzzzz
        )

)

What I want is the following...

Array
(
    [N] => Array
        (
            [68] => sssssss ttttttt
            [69] => uuuuuu vvvvvvvv
            // only C are added here with N
            [04] => wwwwww wwwwwww
            [06] => iiiiiii iiiiiiii
            [41] => zzzzzzzzzz zzzzzzzzzz

        )

    [D] => Array
        (
            [05] => zzzzzzzz zzzzzzzz
            [07] => tttttttttttt ttttttttttt
        )

    [P] => Array
        (
            [88] => yyyyyyy zzzzzzzz
        )

    [C] => Array
        (
            [04] => wwwwww wwwwwww
            [06] => iiiiiii iiiiiiii
            [41] => zzzzzzzzzz zzzzzzzzzz
        )
)

I need the C-Element to be added to N, while all the remaining stay as they are, including the C itself.

How do I accomplish that?


Solution

  • Pretty straightforward stuff; just add the two arrays together like this:

    // add C to N
    $arr['N'] += $arr['C'];
    

    If you don't know what the key names are and you just want to target the first and last item:

    reset($arr); $first = key($arr);
    end($arr); $last = key($arr);
    
    $arr[$first] += $arr[$last];