3

我编写了一个脚本,用于从数据库中返回案例记录。当实际上有两条记录时,我为我的 mysql 查询返回一条记录。这就是我要返回的内容:

{ "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), "] }";
4

2 回答 2

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) . '}';
}
于 2012-07-12T17:32:53.073 回答
2

你需要遍历所有行,你只是得到一个。

另外,不要尝试自己构建 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));
于 2012-07-12T17:42:13.867 回答