0

I am trying to generate nested json data like in this example from one mysql table.

var data = {
"62" : {
    "section" : "bodyImage",
    "img" : "imageurl/image62.png",
    "label" : "blue",
    "price" : "100"
},
"63" : {
    "section" : "bodyImage",
    "img" : "imageurl/image63.png",
    "label" : "red",
    "price" : "120"
}
}

62 and 63 are from the row data_id in the following table:

+-----------+------------+-------------------------+-------+---------+
| data_id   | section    | img             | label | price   | 
+-----------+------------+-------------------------+-------+----------
| 62        | bodyImage  | imagpath/image62.png    |  blue | 100     |
| 63        | bodyImage  | imagpath/image62.png    |  red  | 120     | 
+-----------+------------+-------------------------+-------+---------

+

This is the php file with the query:

$result = mysql_query("SELECT data_id, section, img, label, price FROM table WHERE active != 'no'");

$data = array();

while($row=@mysql_fetch_object($result)) {

$data[] = array (

    'section' => $row['sub_section'],
    'img' => $row['big_image'],
    'label' => $row['label_client_en'],
    'price' => $row['price']

);

}
echo json_encode( $data );

I cannot get it working. Please help me with the right syntax for the multi-dimensional array.

1 Answer 1

1

You cannot json_encode "sub arrays" directly on the main array

You must do json_encode for each array in your while:

$data[] = json_encode(array (

'section' => $row['sub_section'],
'img' => $row['big_image'],
'label' => $row['label_client_en'],
'price' => $row['price']
));

And then you must also encode the main array as you already do.

Sign up to request clarification or add additional context in comments.

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.