繁体   English   中英

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

[英]PHP - Push data to array in foreach loop

我想实现以下数组格式:

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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM