2012-07-12 62 views
2

我有一個我寫的腳本來返回數據庫外的記錄。實際上有兩條記錄時,我爲mysql查詢返回一條記錄。這就是我回到:在PHP數組中顯示多行

{ "cases": [ {"name":"Test Case for App","number":"3846"}] } 

我應該看到:

{ "cases": [ {"name":"Test Case for App","number": "2903"}, {"name":"Test Case 2","number": "2856"} ] } 

這裏是我的源:

$sql = "select * from cases as c join contacts_cases as conc on c.id = conc.case_id where conc.contact_id = '1b360507'"; 
$query = mysql_query($sql); 

// If we find a match, create an array of data, json_encode it and echo it out 
if (mysql_num_rows($query) > 0) 
{ 
    $row = mysql_fetch_assoc($query); 
    $response = array( 
     'name' => $row['name'], 
     'number' => $row['case_number'] 
    ); 

    echo '{ "cases": [ ', json_encode($response), "] }"; 
+2

您可能想要在那裏使用循環來獲取所有值。 – inhan 2012-07-12 17:34:51

回答

6

如果你期望不止一個結果,你應該嘗試

if (mysql_num_rows($query) > 0) 
{ 
    $responses = array(); 
    while($row = mysql_fetch_assoc($query)) { 
     $responses[] = array( 
      'name' => $row['name'], 
      'number' => $row['case_number'] 
     ); 
    } 
    echo '{"cases": ' . json_encode($responses) . '}'; 
} 
1

您需要遍歷所有t他排隊,你只是得到一個。

另外,不要嘗試自己構建JSON。使陣列如何,然後json_encode整個事情。

$cases = array(); 
while ($row = mysql_fetch_assoc($query)) { 
    $cases[] = array( 
     'name' => $row['name'], 
     'number' => $row['case_number'] 
    ); 
} 

echo json_encode(array('cases' => $cases)); 
+0

@hakre:感謝您清理我的代碼。我開始用完咖啡因。 – 2012-07-12 17:51:06