PHP / MySQL çok boyutlu JSON dizi oluşturmak

3 Cevap php

Ben aşağıda örnekteki gibi görünen bir JSON nesnesi oluşturmak istiyorum.


{
    "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" 
}

İlk bölüm mysql_fetch_assoc ve array_push kullanarak bir MySQL veritabanı oluşturulabilir:

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

3 Cevap

Deneyin:

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

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

$json = json_encode($array);

Bu hile yapmak gerekir

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

Ilgili daha fazla bilgi json_encode ve arrays

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

Ve sonra geri dönüş dizi json_encode ve ayarlamak gerekir.