Search code examples
phparraysarray-merge

Merge 2 JSON arrays (Zip effect)


I am no master of the array! I am trying to merge 2 JSON arrays that are related to each other. Essentially Values A and E exist in 1 array while their index (0,1,2 etc) exist in the other. These are examples of my 2 JSONS...

JSON1:

"d": [{"A": 0,"B": "foo1","C": "bar1","D": "real1","E": 0},
      {"A": 1,"B": "foo2","C": "bar2","D": "real2""E": 1},
      {"A": 2,"B": "foo3","C": "bar3","D": "real3","E": 2} ]

JSON 2:

    "A": ["this1","this2","this3"]
    "E": ["last1","last2","last3"]

How can I join using PHP so that the completed version looks like:

"d": [{"A": "this1","B": "foo1","C": "bar1","D": "real1","E": "last1"},
      {"A": "this2","B": "foo2","C": "bar2","D": "real2","E": "last2"},
      {"A": "this3","B": "foo3","C": "bar3","D": "real3","E": "last3"}]

Solution

  • After decoding the JSON to arrays, you can loop over the first one, checking to see if the array key exists in the second array, and if so, replacing the value with the corresponding one from the array in the second array:

    $array1 = json_decode($json1, true);
    $array2 = json_decode($json2, true);
    
    foreach ($array1['d'] as &$arr) {
        foreach ($arr as $key => &$value) {
            if (array_key_exists($key, $array2)) {
                $value = $array2[$key][$value];
            }
        }
    }
    echo json_encode($array1);
    

    Output:

    {
        "d": [
            {
                "A": "this1",
                "B": "foo1",
                "C": "bar1",
                "D": "real1",
                "E": "last1"
            },
            {
                "A": "this2",
                "B": "foo2",
                "C": "bar2",
                "D": "real2",
                "E": "last2"
            },
            {
                "A": "this3",
                "B": "foo3",
                "C": "bar3",
                "D": "real3",
                "E": "last3"
            }
        ]
    }
    

    Demo on 3v4l.org