将MySQL查询转换为JSON编码

时间:2018-09-01 18:14:56

标签: php json codeigniter

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

我该怎么办?请帮助我

1 个答案:

答案 0 :(得分: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,
...

那会更干净。