Rye
Rye

Reputation: 189

merge array inside foreach loop

I want to merge array result inside foreach loop. Is there any solution about this or other best way. Thanks in advance.

PHP code

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

Upvotes: 0

Views: 66

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

The nearest you will get is by building up an array of the data in the foreach loop and JSON encoding the result...

$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.

Upvotes: 2

Related Questions