我写了一个脚本来从数据库中返回案例的记录。当实际上有两条记录时,我为我的 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), "] }";
最佳答案
如果您期待多个结果,您应该尝试
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) . '}';
}
关于php - 在 PHP 数组中显示多行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11457343/