简体   繁体   中英

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

在此处输入图片说明

Here is the result when i run the script.

在此处输入图片说明

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

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);

The problem is because of this line here,

$option[$row['item_option_name']]=explode(',',$value);

In each iteration of while() loop, you're appending the previously calculated $options array to $all . Instead, create an temporary array to hold intermediate result and append that to $all in each iteration, like this:

while($row=$statement->fetch()){
    $opArray = array();
    $value=str_replace('"','',$row['item_option_value']);
    $opArray[$row['item_option_name']]=explode(',',$value);
    $all[$row['oid']]=$opArray;

}   
echo json_encode($all);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM