我有一个数组结构,其中包含一个锦标赛玩家的ID:
array (
0 =>
array (
0 =>
array (
'player' => 7,
'gol' => 1,
),
1 =>
array (
'player' => 9,
'gol' => 1,
),
),
1 =>
array (
0 =>
array (
'player' => 10,
'gol' => 1,
),
1 =>
array (
'player' => 9,
'gol' => 1,
),
),
),
此数组有一些重复项(“玩家”)。我将生成一个不包含玩家重复项的数组,其结果将是玩家每个目标的总和,例如:
array(
0 =>
array (
'player' => 7,
'gol' => 1,
),
1 =>
array (
'player' => 9,
'gol' => 2,
),
2 =>
array (
'player' => 10,
'gol' => 1,
),
),
这是我的代码:
if ($query->have_posts()) {
$players = [];
while ($query->have_posts()) {
$query->the_post();
if (have_rows('field_name', $id)):
while (have_rows('field_name', $id)) : the_row();
$tmp = [];
$player = get_sub_field('player_name', $id);
$tmp['player'] = $player['ID'];
$tmp['gol'] = get_sub_field('player_goal', $id);
array_push($players, $tmp);
}
}
答案 0 :(得分:2)
$games = array (
array(array("player"=>7,"gol"=>1),array("player"=>9,"gol"=>1)),
array(array("player"=>10,"gol"=>1),array("player"=>9,"gol"=>1)),
); //Input array
$player = array();
foreach($games as $game) foreach($game as $gol) //For game and gol
@$player[$gol["player"]]+=$gol["gol"]; //sum gols
arsort($player); //sort by value
print_r($player);
输出
Array
(
[9] => 2
[10] => 1
[7] => 1
)
答案 1 :(得分:1)
幼稚的方式(我从FAEWZX答案中获取了样本):
$games = array (
array(array("player"=>7,"gol"=>1),array("player"=>9,"gol"=>1)),
array(array("player"=>10,"gol"=>1),array("player"=>9,"gol"=>1)),
);
$player = array();
foreach($games as $game)
{
foreach($game as $gol)
{
if(in_array($gol['player'], array_column($player, 'player')))
{
foreach($player as $key => $value)
{
if($value['player'] == $gol['player'])
{
$player[$key]['gol'] += $gol['gol'];
break;
}
}
}
else
{
$player[] = $gol;
}
}
}
print_r($player);
输出:
Array
(
[0] => Array
(
[player] => 7
[gol] => 1
)
[1] => Array
(
[player] => 9
[gol] => 2
)
[2] => Array
(
[player] => 10
[gol] => 1
)
)