oli*_*rbj 3 php arrays foreach
我想实现以下数组格式:
{
"success": true,
"results": [
{
"name" : "Choice 1",
"value" : "value1",
"text" : "Choice 1"
},
{
"name" : "Choice 2",
"value" : "value2",
"text" : "Choice 2"
}
]
}
Run Code Online (Sandbox Code Playgroud)
但是,我使用PHP和foreach循环,从我的数据库返回一些值:
//Search for clients in our database.
$stmt = $dbh->prepare("SELECT * FROM customers");
$stmt->execute();
$showAll = $stmt->fetchAll();
Run Code Online (Sandbox Code Playgroud)
然后我有了我的第一部分数组,以及我的foreach循环:
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data_array[] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
Run Code Online (Sandbox Code Playgroud)
以上仅输出:
[
{
"name":"Choice 1",
"value":"value 1",
"text":"Choice 1"
},
{
"name":"Choice 2",
"value":"value2",
"text":"Choice 2"
}
]
Run Code Online (Sandbox Code Playgroud)
所以它缺少原始数组的顶部 - 但我想循环遍历每个数据库的结果 "results": [ ... ]
试试这个
$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);
Run Code Online (Sandbox Code Playgroud)
创建$data_array数组后,只需在我的帖子中添加几行.
在此处尝试此代码段(带示例输入)
ini_set('display_errors', 1);
foreach ($showAll as $client)
{
$data_array[] = array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
// add these lines to your code.
$result=array();
$result["success"]=true;
$result["results"]=$data_array;
echo json_encode($result);
Run Code Online (Sandbox Code Playgroud)