我想实现以下数组格式:
{
"success": true,
"results": [
{
"name" : "Choice 1",
"value" : "value1",
"text" : "Choice 1"
},
{
"name" : "Choice 2",
"value" : "value2",
"text" : "Choice 2"
}
]
}
但是,我使用PHP和foreach循环,从我的数据库中返回一些值:
//Search for clients in our database.
$stmt = $dbh->prepare("SELECT * FROM customers");
$stmt->execute();
$showAll = $stmt->fetchAll();
然后我得到了数组的第一部分,以及我的foreach循环:
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data_array[] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
以上仅输出:
[
{
"name":"Choice 1",
"value":"value 1",
"text":"Choice 1"
},
{
"name":"Choice 2",
"value":"value2",
"text":"Choice 2"
}
]
所以它缺少原始数组的顶部 - 但是我想在"results": [ ... ]
答案 0 :(得分:6)
试试这个
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data['results'][] = array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
$data['success'] = true; // if you want to update `status` as well
echo json_encode($data);
答案 1 :(得分:5)
答案 2 :(得分:1)
试试这个,因为你在Key“Results”上的$ data_array中有一个数组,所以你也应该使用“results”作为键,然后尝试推送该数组中的数据
foreach ($showAll as $client) {
$data_array["results"][] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
答案 3 :(得分:0)
您只需使用json_encode并将其推送到结果数组
即可$data = array(
"success" => false,
"results" => array()
);
$result = [
[
"name" => "Choice 1",
"value" => "value 1",
"text" => "Choice 1"
],
[
"name" => "Choice 2",
"value" => "value2",
"text" => "Choice 2"
]
];
$data['results'] = json_encode($result);