将mysql查询转换为json编码

问题描述 投票:0回答:1

我有问题转换查询到json编码

这是代码:

$list = $this->M_Bio->dataBio();
$data = array();
foreach ($list as $result) {
$row = array();
$row[] = ['name' => $result->fullname];
$row[] = ['position' => $result->position];
$row[] = ['office' => $result->office];
$row[] = ['extn' => $result->phone];
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);

结果json编码:

{"data": [
["name": "Tiger Nixon","position": "System Architect","office": "Edinburgh","extn": "5421"],["name": "Cedric Kelly","position": "Senior Javascript Developer", "office": "Edinburgh","extn": "6224"]
    ]
}

我想要这样的结果:

    {
    "data": [
    {
    "name": "Tiger Nixon",
    "position": "System Architect",
    "office": "Edinburgh",
    "extn": "5421"
    },
    {
    "name": "Cedric Kelly",
    "position": "Senior Javascript Developer",
    "office": "Edinburgh",
    "extn": "6224"
    }
    ]
    }

我该怎么办?请帮我

php json codeigniter
1个回答
2
投票

您需要更改将所有数据添加到$output数组中的方式...

$row = array();
$row['name'] = $result->fullname;
$row['position'] = $result->position;
$row['office'] = $result->office;
$row['extn'] =$result->phone;
$data[] = $row;

这将为您提供输出数组中更清晰的结果。

你可以一次性建造它们......

$data[] = array('name' => $result->fullname,
     'position' => $result->position,
...

哪个更干净。

© www.soinside.com 2019 - 2024. All rights reserved.