2009-12-17 2 views
1

에서 멀티 dimentional JSON 배열 생성합니다. 내가 아래의 예처럼 보이는 JSON 객체를 생성 할 PHP/MySQL을


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

첫번째 부분

는 mysql_fetch_assoc를 사용 MySQL 데이터베이스에서 생성 array_push 될 수

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

번째 부분은 프로그램의 프로그램의 끝에 첨부되어야한다. 나는 문제가 내가 원하는 것을 할 PHP에서 배열을 조작하는 데 문제 ...

답변

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

그리고 반환 배열은, 당신은 설정해야합니다로 json_encode.

1

이 트릭을 할해야 json_encode

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

점점 더 arrays

8

시도 :

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

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

$json = json_encode($array); 
관련 문제