改变 JSON 输出?

huangapple go评论79阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月16日 09:24:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定