更改json输出?

r55awzrz  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(128)

如何修复我所做的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]}

如何解决?
谢谢

wvyml7n5

wvyml7n51#

您正在将数据编码到单个$data数组中。您需要单独聚合它们,然后将它们放入父数组中。要获得预期的输出,请执行以下操作:

$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);

相关问题