1

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?

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.