gosulove gosulove - 2 months ago 9
JSON Question

php encode nested json in wrong format

I trying to test display a nested Json structure but the result is in wrong format.

php

while($row=$statement->fetch()){

$value=str_replace('"','',$row['item_option_value']);
$option[$row['item_option_name']]=explode(',',$value);
$all[$row['oid']]=$option;

}
echo json_encode($all);


mysql databas structure

enter image description here

Here is the result when i run the script.

enter image description here

I want the json structure to be the right side of the screenshot. Anyone knows what's wrong?

Answer

You would need to empty the $option arrays then like this:

$option = []; //or $option = array(); in PHP < 5.4

This is needed in order not to keep storing the data from the previous iteration.

So:

while($row=$statement->fetch()){

    $value=str_replace('"','',$row['item_option_value']);
    $option = [];
    $option[$row['item_option_name']]=explode(',',$value);
    $all[$row['oid']]=$option;

}   
echo json_encode($all);