PHP-将数据推入数组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();

i然后有阵列的第一部分,而我的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": [ ... ]

中循环

尝试此

$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);

创建$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);

尝试一下,因为您在密钥"结果"上的$ data_array中有一个数组,因此您也应该将"结果"用作键,然后尝试在该数组中推动数据

foreach ($showAll as $client) {  
               $data_array["results"][] = 
                     array(
                     'name' => $client['name'],
                     'value' => $client['name'],
                     'text' => $client['name']
                );
}

您可以简单地使用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);

最新更新