0

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
1
  • 3
    You can't have an object in JSON that has the same key more than once - your desired output doesn't make sense. Commented May 4, 2018 at 14:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.