Reputation: 147
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"}}
Upvotes: 0
Views: 52
Reputation: 2201
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.
Upvotes: 2