Skip to content
Advertisement

Merging JSON while keeping key layout

I’m trying to merge multiple JSON results that I get from an API into a single one.

The JSON data I’m receiving looks like the following:

JavaScript

Here’s the code I’m going with so far:

JavaScript

The desired result would be:

JavaScript

However, I’m receiving:

JavaScript

How would I go about changing this so the keys stay intact and the additional items are added to “articleCollection”?

Advertisement

Answer

As it’s difficult to test properly, this code is as close as I can guess at.

The problem is that when you add the data in with $jsonCombined[], this will just add the data to the end of the array in a numerical sequence. This code instead gets the key along with the content in lines like…

JavaScript

and then uses this key to add the data with the key…

JavaScript

The inner loop which fetches the pages of data, only copies the "articleCollection" elements, this time using $jsonCombined["articleCollection"][] to just keep on adding the data (this bit is the part I’m not sure exactly if this works OK.)

JavaScript

The last foreach may not be needed as it just copies the data from $jsonArr to $jsonCombined. So you could just assign the one to the other.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement