英文:
Change the json output?
问题
我应该如何修复我已经创建的JSON编码?
我的实际代码:
foreach ($list->result_array() as $row) {
foreach ($row as $key => $val) {
$data[] = $val;
}
}
$output = array(
"data" => $data,
);
echo json_encode($output);
实际输出:
{"data":["X1.1",2,2,2,3,1,4,"X1.2",1,1,1,1,2,3,"X1.3",2,3,1,2,2,5,"X1.4",2,2,2,3,5,6]}
而这是我需要的输出:
{"data":["X1.1",2,2,2,3,1,4],["X1.2",1,1,1,1,2,3],["X1.3",2,3,1,2,2,5],["X1.4",2,2,2,3,5,6]}
如何解决它?谢谢!
英文:
How do I fix the json encode that I have made?
my actual code
foreach ($list->result_array() as $row) {
foreach ($row as $key => $val) {
$data[] = $val;
}
}
$output = array(
"data" => $data,
);
echo json_encode($output);
Actual output:
{"data":["X1.1",2,2,2,3,1,4,"X1.2",1,1,1,1,2,3,"X1.3",2,3,1,2,2,5,"X1.4",2,2,2,3,5,6]}
And this is output I need:
{"data":["X1.1",2,2,2,3,1,4],["X1.2",1,1,1,1,2,3],["X1.3",2,3,1,2,2,5],["X1.4",2,2,2,3,5,6]}
How to solve it?
Thanks
答案1
得分: 1
你正在将数据编码为一个名为 $data
的单一数组。您需要分别汇总它们,然后将它们放入一个父数组中,以获得预期的输出:
$output = array(
'data' => array(),
);
foreach ($list->result_array() as $row) {
$data = array();
foreach ($row as $key => $val) {
$data[] = $val;
}
$output['data'][] = $data; // 在这里汇总它们
}
echo json_encode($output);
英文:
You are encoding the data into a single $data
array. You need to aggregate them separately then put them into a parent array. To get the expected output:
$output = array(
'data' => array(),
);
foreach ($list->result_array() as $row) {
$data = array();
foreach ($row as $key => $val) {
$data[] = $val;
}
$output['data'][] = $data; // aggregate them here
}
echo json_encode($output);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论