将 mysql 查询转换为 json 编码



我在将查询转换为 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"
}
]
}

我该怎么办?请帮助我

您需要更改将所有数据添加到$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,
...

这会更干净。

相关内容

  • 没有找到相关文章

最新更新