tags:

views:

113

answers:

3

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...

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

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

mabwi
A: 

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

Juan
+2  A: 

Try:

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

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

$json = json_encode($array);
K Prime