[英]PHP create nested array and pass back with json_encode
I have the following, and while $data['details']
is being populated OK, there should be three results in $data['tests']
, but "tests" isn't showing at all in the JSON result: 我有以下内容,虽然$data['details']
已填充为好,但$data['tests']
应该有三个结果,但JSON结果中根本没有显示“ tests”:
{"details":["Clinical result","Signature result"]} {“详细信息”:[“临床结果”,“签名结果”]}}
$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);
If I change the above to the following then I get only the last record for $row['lab_test_group_fk']
, not all three records for that column (hence the foreach loop as above): 如果将上面的内容更改为以下内容,那么我只会获得$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);
{"details":["Clinical result","Signature result"],"tests":["21"]} {“详细信息”:[“临床结果”,“签名结果”],“测试”:[“ 21”]}
What am I doing wrong here? 我在这里做错了什么?
Thanks to Tamil Selvin this was the solution that worked for me: 感谢泰米尔·塞尔文,这是对我有用的解决方案:
$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);
Which returned: 哪个返回:
{"details":["Clinical result","Signature result"],"tests":[["31"],["2"],["21"]]} {“详细信息”:[“临床结果”,“签名结果”],“测试”:[[“ 31”],[“ 2”],[“ 21”]]}
$data['tests'] = array($group);
means reassign $data['tests']
to a new value again. 表示再次将$data['tests']
重新分配$data['tests']
新值。
Try $data['tests'][] = array($group);
尝试$data['tests'][] = array($group);
. 。
Try 尝试
$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);
or 要么
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);
You are overwriting existing data of $data. 您正在覆盖$ data的现有数据。 You need some kind of array where you will put all your records. 您需要将所有记录都放在其中的某种数组。 Try this 尝试这个
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.