0

I am trying to create json array to fill a datatable with code in php The fields should be:

{
 "data": [
 {
 "RecordID": 1,
 "OrderID": "61715-075",
 "Country": "China",
 "ShipCountry": "CN",
 },
 {
 "RecordID": 2,
 "OrderID": "63629-4697",
 "Country": "Indonesia",
 "ShipCountry": "ID",
 },
 {
 "RecordID": 3,
 "OrderID": "68084-123",
 "Country": "Argentina",
 "ShipCountry": "AR",
 }
 ]
}

I tried to do this just for testing the fields $array = array('one', 'two', 'three', 'four');

 foreach ($array as $key => $value) {
 $temp['data'] = array(
 'RecordID' => 1, 
 'Country' => "Indonesia",
 'CompanyName' => "Indonesia"
 );
 echo json_encode($temp);
 }

But its returning

{"data":{"RecordID":1,"Country":"Indonesia","CompanyName":"Indonesia"}}{"data":{"RecordID":1,"Country":"Indonesia","CompanyName":"Indonesia"}}{"data":{"RecordID":1,"Country":"Indonesia","CompanyName":"Indonesia"}}{"data":{"RecordID":1,"Country":"Indonesia","CompanyName":"Indonesia"}}
asked May 6, 2019 at 9:45
1
  • Try - $temp['data'] = array .... & json_encode outside the loop. Commented May 6, 2019 at 9:58

1 Answer 1

2

You are building multiple JSON-strings. To have one containing all your data, all you have to do is to encode the most outer array (in your case this seems to be $array).

So doing this is enough:

echo json_encode($array);

You have to call the json_encode function after you are done preparing your data, so in this case after your loop.

answered May 6, 2019 at 9:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.