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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43514533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:51:02  来源:igfitidea点击:

PHP - Push data to array in foreach loop

phparraysforeach

提问by oliverbj

I want to achieve below array format:

我想实现以下数组格式:

{
    "success": true,
    "results": [
      {
        "name"  : "Choice 1",
        "value" : "value1",
        "text"  : "Choice 1"
      },
      {
        "name"  : "Choice 2",
        "value" : "value2",
        "text"  : "Choice 2"
      }
    ]
}

However, I am using PHP and a foreach loop, to return some values from my database:

但是,我使用 PHP 和 foreach 循环从我的数据库中返回一些值:

//Search for clients in our database.
$stmt = $dbh->prepare("SELECT * FROM customers");
$stmt->execute();
$showAll = $stmt->fetchAll();

I then have my first part of the array, and my foreach loop:

然后我有了数组的第一部分,以及我的 foreach 循环:

$data = array(
    "success" => false,
    "results" => array()
);

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

}

Above only outputs:

以上仅输出:

[
 {
   "name":"Choice 1",
   "value":"value 1",
   "text":"Choice 1"
 },
 {
   "name":"Choice 2",
   "value":"value2",
   "text":"Choice 2"
 }
]

So it is missing the top part of my original array - but I want to loop through each database results in "results": [ ... ]

所以它缺少我原始数组的顶部 - 但我想遍历每个数据库结果 "results": [ ... ]

回答by Farooq Ahmed Khan

Try this

尝试这个

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

回答by Sahil Gulati

After creating $data_arrayarray just add few lines which i have in my post.

创建$data_array数组后,只需在我的帖子中添加几行即可。

Try this code snippet here(with sample input)

在此处尝试此代码片段(带有示例输入)

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

回答by Badshah Sahib

try this as you have an array inside the $data_array on Key "Results" so you should use "results" as a key also and then try to push data in that array

试试这个,因为你在 $data_array 键“结果”上有一个数组,所以你也应该使用“结果”作为键,然后尝试在该数组中推送数据

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

}

回答by Priyank

You can simply use json_encode and push it to your result array

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