2012-12-15 73 views
0

我從代碼需要從PHP獲取JSON格式

$rt = array(); 
$rt["service"]["title"] = karthik; 
$rt["service"]["city"] = chennai; 

$t = array(); 
$t["service"]["title"] = siva; 
$t["service"]["city"] = madurai; 

echo json_encode(array($rt,$t)); 

得到一個JSON格式像這樣

[{"service":{"title":"karthik","city":"chennai"}},{"service":{"title":"siva","city":"madurai"}}] 

,但我需要的JSON結果相同的格式從本代碼

$a=mysql_query("SELECT title,city,category,parentid,pay,task.id 
FROM task"); 
while($row=mysql_fetch_array($a)) 
{ 
$jsonrow=new stdClass; 
$jsonrow->title=$row['title']; 
$jsonrow->city=$row['city']; 


$jsonresponse=new stdClass; 
$jsonresponse->service=$jsonrow; 

} 

echo json_encode(array($jsonresponse)); 

但結果實際上我從上面的代碼得到的是

[{"service":{"title":"Event Help","city":"Santa Fe"}}] 

請幫助我的人對這個問題.....

+5

這裏有什麼問題返回所有的值?這兩個json看起來相同 – GBD

+0

我需要這樣的結果[{「service」:{「title」:「karthik」,「city」:「chennai」}},{「service」:{「title」:「siva」, 「城市」:「馬杜賴」}}] –

+0

檢查了這一點 - http://stackoverflow.com/questions/13156159/json-menu-structure-from-mysql/13157562#13157562 並重新思考 – Joddy

回答

3

使用數組存儲從查詢

$array = array(); 
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id 
FROM task"); 
while($row=mysql_fetch_array($a)) 
{ 
    $jsonrow=new stdClass; 
    $jsonrow->title=$row['title']; 
    $jsonrow->city=$row['city']; 


    $jsonresponse=new stdClass; 
    $jsonresponse->service=$jsonrow; 
    $array[] = $jsonresponse; 
} 

echo json_encode(array($array)); 
+0

感謝男士爲你的答案其工作正常,因爲我期望 –

0

嘗試這樣

$a=mysql_query("SELECT title,city,category,parentid,pay,task.id FROM 
    task"); 

    $jsonrow=new stdClass; 
    $jsonresponse=new stdClass; 
    while($row=mysql_fetch_array($a)) { 

    $jsonrow->title=$row['title']; $jsonrow->city=$row['city'];  
    $jsonresponse->service=$jsonrow; 

    } 
1

你在你的while循環中覆蓋$jsonresponse,你應該將它添加到數組中並且json_encode這個數組

$response = array(); 

while(...){ 
    ... 
    $response[] = $jsonresponse; 
} 
echo json_encode($response); 
+0

感謝男士爲你的回答工作正常,因爲我期望 –