我想将 sandra_array 的值与 john_array 进行比较,然后与 sem_array 进行比较。
我可以将 sandra_array 与 john_array 进行比较:
ol {
list-style-image: url('your_image_url');
}
结果
<?php
$sandra_array = array("soccer" => "10", "basketball" => "20", "atletics" => "40");
$john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");
$sem_array = array("soccer" => "5", "basketball" => "10", "atletics" => "50");
$common_sports = array_keys(array_intersect_key($sandra_array, $john_array));
$points_sandra_array = $points_john_array = array_fill_keys($common_sports, 0);
foreach ($common_sports as $common_sport) {
if ($sandra_array[$common_sport] > $john_array[$common_sport]) {
$points_sandra_array[$common_sport]++;
} else if ($sandra_array[$common_sport] < $john_array[$common_sport]) {
$points_john_array[$common_sport]++;
}
}
foreach ($common_sports as $common_sport) {
}
echo "Sandra (", array_sum($points_sandra_array).") vs John (", array_sum($points_john_array).")";
?>
我想也有Sandra对抗Sem的结果。像这样:
Sandra (1) vs John (2)
我正在考虑制作以下多维数组:
Sandra (1) vs John (2)
Sandra (2) vs Sem(1)
然后在foreach中,我首先将Sandra的点数与John的点数进行比较,然后与Sem的点数进行比较。但我不知道该怎么做。
你能帮我解决这个问题吗?
答案 0 :(得分:1)
解决方案是:
首先声明一个包含对手玩家阵列的数组,如下所示:
$players_array = array('John' => $john_array, 'Sem' => $sem_array);
然后循环每个对手玩家计算最终得分。
所以你的代码应该是这样的:
$sandra_array = array("soccer" => "10", "basketball" => "20", "atletics" => "40");
$john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");
$sem_array = array("soccer" => "5", "basketball" => "10", "atletics" => "50");
// Declare an array containing opponents players' array
$players_array = array('John' => $john_array, 'Sem' => $sem_array);
// Loop through each opponent player to calculate the final score
foreach($players_array as $opponent_player => $opponent_player_array){
$common_sports = array_keys(array_intersect_key($sandra_array, $opponent_player_array));
$points_sandra_array = $points_opponent_array = array_fill_keys($common_sports, 0);
foreach ($common_sports as $common_sport) {
if ($sandra_array[$common_sport] > $opponent_player_array[$common_sport]) {
$points_sandra_array[$common_sport]++;
} else if ($sandra_array[$common_sport] < $opponent_player_array[$common_sport]) {
$points_opponent_array[$common_sport]++;
}
}
echo "Sandra (". array_sum($points_sandra_array).") vs {$opponent_player} (". array_sum($points_opponent_array) .")<br />";
}
输出:
Sandra (1) vs John (2)
Sandra (2) vs Sem (1)