我遇到了问题,我正在尝试解析从网址动态更新的json文件。我遇到的第一个问题是,json文件只生成对象而没有数组(见ex.1)。
(例1)
[{"title":"ThisIsTitle1","Team1":"ThisIsTeam1","Team2":"ThisIsTeam2","Result":"ThisIsTeam1"}{"title":"ThisIsTitle2","TeamX":"ThisIsTeamX","TeamY":"ThisIsTeamY","Result":"ThisIsTeamY"}]
因为我不知道如何在没有数组的情况下解析字符串,所以我在网上查找了一下,找到了为每个对象动态添加数组的方法; (见ex.2& ex.3)
(例2)我上网的内容
$json_string = 'http://myurl/pathtojsonfile';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "<pre>";
print_r($obj);
(ex.3)结果是什么
Array
(
[0] => Array
(
[Title] => ThisIsTitle1
[Team1] => ThisIsTeam1
[Team2] => ThisIsTeam2
[Result] => ThisIsTeam1
)
[0] => Array
(
[Title] => ThisIsTitle2
[TeamX] => ThisIsTeamX
[TeamY] => ThisIsTeamY
[Result] => ThisIsTeamY
)
)
现在这是我的问题:我正在尝试在同一个表格中显示所有TeamX和TeamY,并在其他单元格中添加其旁边的平均结果。表示每个团队的胜利和deafeat平均数。
你需要知道的事情:
[Result] => ThisIsTeamZ
;意味着团队中没有一个因某种原因获胜。我知道我向你们提出了很多要求,但我是一个菜鸟,我学习起来很慢。如果你能帮助我,那么你会受到欢迎。如果你需要我的任何东西,请不要犹豫。
答案 0 :(得分:0)
如果没有合适的JSON样本,我只能对您有权访问的实际数据格式做出假设。
您需要以可用的方式重新格式化该数据。例如,索引是团队的数组&#39;名称,值是包含相关值的索引victories
,defeats
和draws
的数组。
这是通过循环JSON,检查哪个团队赢得了每个结果(如果有)并增加相关值(victories
,defeats
,draws
)来完成的。< / p>
$teams = array();
foreach($obj as $result) {
// team names
$teamName1 = $result['team1'];
$teamName2 = $result['team2'];
// initialize team 1 array at zero if it does not exist
if(!isset($teams[$teamName1])) {
$teams[$result['team1']] = array('victories'=>0, 'defeats'=>0, 'draws'=>0);
}
// initialize team 2 array at zero if it does not exist
if(!isset($teams[$teamName2])) {
$teams[$teamName2] = array('victories'=>0, 'defeats'=>0, 'draws'=>0);
}
// team 1 wins
if($result['Result'] == $teamName1) {
$teams[$teamName1]['victories']++;
$teams[$teamName2]['defeats']++;
}
// team 2 wins
elseif($result['Result'] == $teamName2) {
$teams[$teamName1]['defeats']++;
$teams[$teamName2]['victories']++;
}
// draw
else {
$teams[$teamName1]['draws']++;
$teams[$teamName2]['draws']++;
}
}
然后您可以访问此结构,从而可以使用基本算法:
Array
(
[ThisIsTeamX] => Array
(
[victories] => 98
[defeats] => 76
[draws] => 54
)
[ThisIsTeamY] => Array
(
[victories] => 12
[defeats] => 34
[draws] => 56
)
)
你可以获得这样一支球队的胜利VS失败率:
$winRatio = $teams['ThisIsTeamX']['victories'] / $teams['ThisIsTeamX']['defeats'];
您可以获得此类团队所玩的比赛总数:
$matchesCount = array_sum($teams['ThisIsTeamX']);