我想实现以下数组格式:
{
"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": [ ... ]
原文由 oliverbj 发布,翻译遵循 CC BY-SA 4.0 许可协议
尝试这个