Skip to content
Advertisement

array_merge before json encode in PHP

$myArray = array();

for($i=0;i<2;$i++){
..
.. //get the content logic here

assign it to array
$myArray["item"]["content"] = $item_content;
}
echo json_encode($myArray);

The above code produced this result:

enter image description here

Which has an error because I didn’t merge them.

I tried to merge like this:

$finalJson = array_merge($finalJson, $myArray); 

but the output of echo $finalJson is one object instead of 3.

Advertisement

Answer

Update:

Your real problem is down to your use of array_merge on an associative array. The behaviour of array_merge is to reassign duplicate keys if they are associative (cf the docs):

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

And because $myArray is clearly using strings as keys, the values in $finalJson are being reassigned. What you need to do is either create unique keys on each iteration, or simply push the values of $myArray onto a numerically indexed $finalJson array (like I showed in my original answer below)


The problem is simply this:

$myArray["item"]["content"] = $item_content;

it’s inside the loop, each time reassigning the value of $myArray["item"]["content"], and not adding it to the array. I suspect that what you wanted to do is add this at the bottom of your loop (for each new value of $myArray):

$finalJson[] = $myArray;

Then, on the next iteration, $myArray will be reassigned, and its new value will be appended to the $finalJson variable.

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