PHP JSON解析格式
我正在使用PHP解析JSOn。现在我的json工作正常,我只想格式化我的输出。我已经创建了一个rootobj数组,我在其中插入了一些属性,然后在rootobj中有另一个数组,但我希望内部数组属性位于根元素中,这是我的代码PHP JSON解析格式,php,arrays,json,Php,Arrays,Json,我正在使用PHP解析JSOn。现在我的json工作正常,我只想格式化我的输出。我已经创建了一个rootobj数组,我在其中插入了一些属性,然后在rootobj中有另一个数组,但我希望内部数组属性位于根元素中,这是我的代码 $rootObj = array( MainEvent' => $event_value['MainEvent'], 'OutcomeDateTime' => $formatteddate->format('Y-m-d H:i:s'),
$rootObj = array(
MainEvent' => $event_value['MainEvent'],
'OutcomeDateTime' => $formatteddate->format('Y-m-d H:i:s'),
'OutcomeDateTimeUTC' => gmdate('Y-m-d H:i:s', strtotime($event_value['OutcomeDateTime']))
);
//inner array
foreach($event_value['Competitors']['Competitors'] as $compKey => $compVal) {
$teamName = array_key_exists('Team',$compVal) ? $compVal['Team'] : $compVal['Name'];
$win = $compVal['Win'];
//Creating Competitor Array
$CompetitorArray[] = array(
"Team" => $teamName,
"Win" => $win,
);
}
$rootObj ['Competitors'] = $CompetitorArray;
这是我输出的一个示例
...
"MainEvent": "West Perth v Swan Districts",
"OutcomeDateTime": "2014-07-05 16:05:00",
"OutcomeDateTimeUTC": "2014-07-05 06:05:00",
"Competitors": [
{
"Team": "West Perth",
"Win": "1.57"
},
{
"Team": "Swan Districts",
"Win": "2.35"
}
]
},
{
"MainEvent": "East Fremantle v Perth",
"OutcomeDateTime": "2014-07-05 16:05:00",
"OutcomeDateTimeUTC": "2014-07-05 06:05:00",
"Competitors": [
{
"Team": "East Fremantle",
"Win": "1.22"
},
{
"Team": "Perth",
"Win": "4.15"
}
]
},
{
"MainEvent": "East Perth v Peel Thunder",
"OutcomeDateTime": "2014-07-05 16:05:00",
"OutcomeDateTimeUTC": "2014-07-05 06:05:00",
"Competitors": [
{
"Team": "East Perth",
"Win": "1.12"
},
{
"Team": "Peel Thunder",
"Win": "6.00"
}
]
}
],
.....
但是我希望我的输出是这样的
...
"MainEvent": "West Perth v Swan Districts",
"OutcomeDateTime": "2014-07-05 16:05:00",
"OutcomeDateTimeUTC": "2014-07-05 06:05:00",
"Team1": "West Perth",
"Win1": "1.57",
"Team2": "Swan Districts",
"Win2": "2.35"
},
{
"MainEvent": "East Fremantle v Perth",
"OutcomeDateTime": "2014-07-05 16:05:00",
"OutcomeDateTimeUTC": "2014-07-05 06:05:00",
"Team3": "East Fremantle",
"Win3": "1.22",
"Team4": "Perth",
"Win4": "4.15"
},
{
"MainEvent": "East Perth v Peel Thunder",
"OutcomeDateTime": "2014-07-05 16:05:00",
"OutcomeDateTimeUTC": "2014-07-05 06:05:00",
"Team5": "East Perth",
"Win5": "1.12",
"Team6": "Peel Thunder",
"Win6": "6.00"
}
],,
// outside of scope
$countTeam=0;
...
foreach($event_value['Competitors']['Competitors'] as $compKey => $compVal) {
$countTeam++;
$teamName = array_key_exists('Team',$compVal) ? $compVal['Team'] : $compVal['Name'];
$win = $compVal['Win'];
//Insert to root object
$rootObj["Team".$countTeam] = $teamName;
$rootObj["Win".$countTeam] = $win;
}