这是我想要的JSON输出
{
"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"
}
]
}
这是我的代码
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 );
}
我得到了这个输出。但是输出中缺少逗号。有人能给我一些建议吗?
{
"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"
}
]
}
我已经尝试过这些代码,但我不确定如何添加逗号在我的输出JSON
您必须将根对象包装在另一个数组中:
$rootObjects = [];
foreach ($SortedByDate as $key => $values){
// ...
$rootObjects[] = $rootObj;
}
echo json_encode($rootObjects);
它将输出[{object1}, {object2}, ....]
,即输出包含两个方括号,这两个方括号在您的预期输出中没有出现,但对于使其成为有效的JSON很重要。
打印了两次,不会有逗号;
试试这个:
$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);
对我来说不像一个有效的JSON
让我知道它是否有效