我写了一个脚本来返回数据库中的案例记录。当实际有两条记录时,我正在为我的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), "] }";
答案 0 :(得分: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 :(得分: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));