从PHP/MySQL生成多维JSON数组

rsh*_*hid 1 php json

我想创建一个类似于下面示例的JSON对象.


{
    "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" 
}
Run Code Online (Sandbox Code Playgroud)

第一部分可以使用mysql_fetch_assoc和array_push从MySQL数据库生成:

while ($row = mysql_fetch_assoc($result)) 
{ 
  array_push($returnArray,  $row); 
}
Run Code Online (Sandbox Code Playgroud)

第二部分将附加在程序结束时.我无法在PHP中操作数组来做我想做的事情......

K P*_*ime 8

尝试:

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

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

$json = json_encode($array);
Run Code Online (Sandbox Code Playgroud)