简体   繁体   中英

generate multi-dimentional JSON array from PHP/MySQL

I want to create a JSON object that looks like the example below.


{
    "Products": [
        {
            "ProductNo": "11111",
            "Descr": "Myproduct-1",
            "Price": "225.36"
        },
        {
            "ProductNo": "11112",
            "Descr": "Myproduct-2",
            "Price": "235.46"
        },
        {
            "ProductNo": "11113",
            "Descr": "Myproduct-3",
            "Price": "245.56"
        },
        {
            "ProductNo": "11114",
            "Descr": "Myproduct-4",
            "Price": "255.56"
        } 
    ],
    "DateUpdated" : "20091209",
    "UpdatUser" : "Bob" 
}

The first part can be generated from a MySQL database using mysql_fetch_assoc and array_push:

while ($row = mysql_fetch_assoc($result)) 
{ 
  array_push($returnArray,  $row); 
}

The second part is to be appended at the end of the program in program. I am having trouble manipulating arrays in PHP to do what I want...

Try:

$array = array (
    'Products' => array (),
    'DateUpdated' => '20091209',
    'UpdateUser' => 'Bob',
);

while ($row = mysql_fetch_assoc($result))
    $array['Products'][] = $row;

$json = json_encode($array);

This should do the trick

$productArray = array();
while ($row = mysql_fetch_assoc($result)) 
{ 
  array_push($productArray,  $row); 
}

$returnArray['Products'] = $productArray;
$returnArray['DateUpdated'] = $dateUpdated; // 20091209 in your example
$returnArray['UpdatUser'] = $updatUser; // Bob in your example

$jsonEncoded = json_encode($returnArray);

More on json_encode and arrays

$returnArray['DateUpdated'] = '20091209';
$returnArray['UpdatUser'] = 'Bob';

And then json_encode the return array, and you should be set.

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