Home » Php » Merge multidimensional array values by shared key

Merge multidimensional array values by shared key

Posted by: admin September 25, 2018 Leave a comment

Questions:

Working with a single array in PHP, I’d like to merge like with like and am able to do so but I only get 1 return where there should be 2.

Below is the original array, and the new.

    id LIKE 'fghij' OR id LIKE 'abcde' 

   $orig = Array
    (
        [0] => Array
            (
                [id] => abcde
                [field2] => height
                [value2] => 40 ft.
            )

        [1] => Array
            (
                [id] => abcde
                [field3] => width
                [value3] => 10-15 ft.
            )

        [2] => Array
            (
                [id] => abcde
                [field4] => light
                [value4] => Full - Partial
            )

        [3] => Array
            (
                [id] => abcde
                [field6] => space
                [value6] => 5-6 ft.
            )

        [4] => Array
            (
                [id] => fghij
                [field2] => height
                [value2] => 4-8 ft.
            )

        [5] => Array
            (
                [id] => fghij
                [field3] => width
                [value3] => 3-4 ft.
            )

        [6] => Array
            (
                [id] => fghij
                [field4] => light
                [value4] => Full - Partial
            )

        [7] => Array
            (
                [id] => fghij
                [field5] => season
                [value5] => Spring
            )

        [8] => Array
            (
                [id] => fghij
                [field6] => space
                [value6] => 4 ft.
            )

        [9] => Array
            (
                [id] => fghij
                [field19] => restricted
                [value19] => CA, TX, LA, FL, AZ
            )

        [10] => Array
            (
                [id] => abcde
                [field19] => restricted
                [value19] => AZ
            )

    )
   $new = Array
    (
        [id] => abcde
        [field2] => height
        [value2] => 4-8 ft.
        [field3] => width
        [value3] => 3-4 ft.
        [field4] => light
        [value4] => Full - Partial
        [field6] => space
        [value6] => 4 ft.
        [field5] => season
        [value5] => Spring
        [field19] => restricted
        [value19] => AZ
    )

$new is so close to being correct but it ignores everything relating to fghij, returning a single flattened array. I’d like it to return both id’s with their merged values.

This is where I’m at code wise:

$new_new = [];
foreach($orig as $key => $value){
  if(is_array($value)){
    $new_new = array_merge($new_new, $value);
  }
}
Answers: