在foreach循环中合并数组

时间:2018-05-04 14:10:38

标签: php

我想在foreach循环中合并数组结果。关于这个或其他最佳方式是否有任何解决方案。提前谢谢。

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

1 个答案:

答案 0 :(得分:2)

最接近的是通过在foreach循环中构建数据数组并对结果进行JSON编码...

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

这会停止重复的名称值。

在原始尝试中,您分别对每一行进行编码,因此JSON无效。