PHP - 在foreach循环中将数据推送到数组

时间:2017-04-20 08:46:19

标签: php arrays foreach

我想实现以下数组格式:

{
    "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": [ ... ]

中循环遍历每个数据库结果

4 个答案:

答案 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)

创建)数组后,只需在帖子中添加几行。

Try this code snippet here(带样本输入)     

$data_array

答案 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);