Reputation: 701
This is the JSON output i want
{
"MainEvent":"Geelong v Essendon",
"OutcomeDateTime":"2014-06-27 19:51:00.0000000",
"Competitors":[
{
"Name":"Geelong",
"Win":"1.32"
},
{
"Name":"Essendon",
"Win":"3.40"
}
]
},
{
"MainEvent":"Hawthorn v Gold Coast",
"OutcomeDateTime":"2014-06-28 13:46:00.0000000",
"Competitors":[
{
"Name":"Geedlong",
"Win":"1.32d"
},
{
"Name":"Essenddon",
"Win":"3.40d"
}
]
}
This is my code
foreach ($SortedByDate as $key => $values){
foreach ($json_a as $root_element => $childnode) {
foreach( $childnode as $cKey => $subChild) {
$rootObj = array(
'MainEvent' => $subChild['MainEvent'],
'OutcomeDateTime' => $subChild['OutcomeDateTime'],
foreach($subChild['Competitors']['Competitors'] as $compKey => $compVal) {
$teamName = $compVal['Team'];
$win = $compVal['Win'];
$abc = array(
"Team" => $teamName,
"Win" => $win,
);
}
}
$rootObj ['Competitors'] = $abc;
}}
$abc="";
print json_encode($rootObj );
}
And i am getting this output . But comma is missing in my output. Can anyone give me some suggestions please?
{
"MainEvent":"Geelong v Essendon",
"OutcomeDateTime":"2014-06-27 19:51:00.0000000",
"Competitors":[
{
"Name":"Geelong",
"Win":"1.32"
},
{
"Name":"Essendon",
"Win":"3.40"
}
]
}
{
"MainEvent":"Hawthorn v Gold Coast",
"OutcomeDateTime":"2014-06-28 13:46:00.0000000",
"Competitors":[
{
"Name":"Geedlong",
"Win":"1.32d"
},
{
"Name":"Essenddon",
"Win":"3.40d"
}
]
}
I have tried these code but i am not sure how to add comma in my output JSON
Upvotes: 2
Views: 77
Reputation: 733
You're printing it twice, it will not have comma;
Try this:
$jsons = array();
foreach ($SortedByDate as $key => $values){
foreach ($json_a as $root_element => $childnode) {
foreach( $childnode as $cKey => $subChild) {
$rootObj = array(
'MainEvent' => $subChild['MainEvent'],
'OutcomeDateTime' => $subChild['OutcomeDateTime'],
foreach($subChild['Competitors']['Competitors'] as $compKey => $compVal) {
$teamName = $compVal['Team'];
$win = $compVal['Win'];
$abc = array(
"Team" => $teamName,
"Win" => $win,
);
}
}
$rootObj ['Competitors'] = $abc;
}}
$abc="";
$jsons[] = json_encode($rootObj);
}
print implode(",",$jsons);
doesn't look like a valid JSON to me though
let me know if it works.
Upvotes: 0
Reputation: 173542
You have to wrap the root objects in another array:
$rootObjects = [];
foreach ($SortedByDate as $key => $values){
// ...
$rootObjects[] = $rootObj;
}
echo json_encode($rootObjects);
It will output [{object1}, {object2}, ....]
, i.e. the output includes two square brackets that weren't present in your expected output but are important to make it valid JSON.
Upvotes: 1