PHP创建嵌套数组并使用json_encode传回

时间:2015-01-22 02:09:52

标签: php jquery json

我有以下内容,当$data['details']正在填充时,$data['tests']中应该有三个结果,但是"测试"在JSON结果中根本没有显示:

{"详情":["临床结果","签名结果"]}

$data = array();

while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
foreach($row['lab_test_group_fk'] as $group){
$data['tests'] = array($group);
}
}
echo json_encode($data);

如果我将上面的内容更改为以下内容,那么我只获得$row['lab_test_group_fk']的最后一条记录,而不是该列的所有三条记录(因此上面的foreach循环):

while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
$data['tests'] = array($row['lab_test_group_fk']);
}
echo json_encode($data);

{"详细信息":["临床结果","签名结果"],"测试":[" 21& #34;]}

我在这里做错了什么?

感谢泰米尔塞尔文,这是对我有用的解决方案:

$data = array();

while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
$data['tests'][] = array($row['lab_test_group_fk']);
}
echo json_encode($data);

返回了:

{"详细信息":["临床结果","签名结果"],"测试":[[" 31"],[" 2"],[" 21"]]}

3 个答案:

答案 0 :(得分:1)

$data['tests'] = array($group);表示再次将$data['tests']重新分配给新值。

尝试$data['tests'][] = array($group);

答案 1 :(得分:1)

尝试

$data = array();
while ($row = mysql_fetch_array($result)) {
  $data[]['details'] = array($row['tests_clinical'], $row['signature']);
  $data[]['tests'] = array($row['lab_test_group_fk']);
}
echo json_encode($data);

while ($row = mysql_fetch_array($result)) {
$data[] = array(
     'details' => array($row['tests_clinical'], $row['signature']),
      'tests' => array($row['lab_test_group_fk'])
);
}
echo json_encode($data);

答案 2 :(得分:0)

您正在覆盖$ data的现有数据。你需要某种数组来放置所有记录。试试这个

$data = array();

while ($row = mysql_fetch_array($result)) {

    $record = array();   // this creates new record
    $record['details'] = array($row['tests_clinical'], $row['signature']);
    foreach($row['lab_test_group_fk'] as $group){
         $record['tests'] = array($group);
    }
    $data[] = $record;     // this adds record to data
}
echo json_encode($data);