简体   繁体   English

在foreach循环中合并数组

[英]merge array inside foreach loop

I want to merge array result inside foreach loop. 我想在foreach循环中合并数组结果。 Is there any solution about this or other best way. 是否有关于此或其他最佳方法的解决方案? Thanks in advance. 提前致谢。

PHP code PHP代码

include('Config.php');
$data = json_decode(file_get_contents("php://input"));

foreach($data->dataVal as $key => $value){
 echo json_encode($config->query($key,$value));}

//this is the response code above --> how to merge this 2,3 array result into one only
[{"name":"Roi"}][{"name":"Tom"}][{"name":"Chad"}] 


//result to be expected like this 
[{"name":"Roi","name":"Tom","name":"Chad"}]  // this is i want

The nearest you will get is by building up an array of the data in the foreach loop and JSON encoding the result... 您将获得的最接近的结果是,在foreach循环中构建数据数组,并对结果进行JSON编码...

$result = array();
foreach($data->dataVal as $key => $value){
    $result[] = $config->query($key,$value);
}
echo json_encode($result);

This stops having repeated values for the name. 这不再需要重复的名称值。

In your original attempt, you were encoding each row separately, so the JSON was invalid. 在最初的尝试中,您分别对每一行进行编码,因此JSON无效。

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

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