【发布时间】:2018-06-30 12:06:14
【问题描述】:
我正在尝试通过循环访问 wordpress 中的帖子来创建一个数组,并构建一组人员、他们玩过的游戏以及他们在每场比赛中发布的分数。
我当前的代码:
$world_rank = [];
while ( $the_query->have_posts() ) : $the_query->the_post();
$category = get_the_category();
$cat_name = $category[0]->cat_name;
$score = get_field('score');
$author = get_the_author();
$array_size = sizeof($world_rank[$author]['games']);
if( $array_size < 1 ){
$world_rank[$author]['games'][] = ['name' => addslashes($cat_name), 'scores' => [$score] ];
}else{
// loop through the array and see if they have been similar game names if so, add them to push array
$i = 0;
foreach($world_rank[$author]['games'] as $game){
if($game['name'] == $cat_name){
echo 'Same name ' .$game['scores']. ' score is '.$score.'</br>';
array_push($game['scores'], $score);
// this doesn't seem to work
// break;
}
else if($game['name'] !== $cat_name && $i == $array_size - 1 ){ //
// if the names are not the same create a new array for the other game
$world_rank[$author]['games'][] = ['name' => addslashes($cat_name), 'scores' => [$score] ];
}
$i++;
}
}
endwhile;
上面的输出给出了这个:
$world_rank = array (
'frantheman' =>
array (
'games' =>
array (
0 =>
array (
'name' => 'Candy',
'scores' =>
array (
0 => '23',
),
),
1 =>
array (
'name' => 'PopCorn',
'scores' =>
array (
0 => '25',
),
),
2 =>
array (
'name' => 'Chocolate',
'scores' =>
array (
0 => '5',
),
),
3 =>
array (
'name' => 'Candy',
'scores' =>
array (
0 => '25',
),
),
)
);
我怎样才能使 world_rank 数组具有 'Candy' 值作为 1 数组,因为 'Candy' 值在数组中出现两次,并结合 'Candy' 键的分数。所以让它现在看起来像:
$world_rank = array (
'frantheman' =>
array (
'games' =>
array (
0 =>
array (
'name' => 'Candy',
'scores' =>
array (
0 => '23',
1 => '25'
),
),
1 =>
array (
'name' => 'PopCorn',
'scores' =>
array (
0 => '25',
),
),
2 =>
array (
'name' => 'Chocolate',
'scores' =>
array (
0 => '5',
),
)
);
如您所见,在新数组中,'Candy' 有 2 个用于分数的数组。对此的任何帮助将不胜感激。谢谢。
【问题讨论】:
-
请提供您如何创建第一个数组的代码
-
@Tarasovych 已更新。感谢您的评论让我把它放进去,而不是像其他人那样投反对票。
-
你必须使用
array_push()将所有游戏的分数放入存在数组中,使用foreach() -
谢谢,但我就是这么做的。就在这里:f($game['name'] == $cat_name){ echo 'Same name ' .$game['scores']. ' 分数是 '.$score.''; array_push($game['scores'], $score); // 这似乎不起作用 // break; }
-
如果我在该条件下进行回显,我会看到它在“Candy”名称键处添加到数组中。但是,当我打印数组的最终结果时,我得到了我在问题中显示的第一个输出。
标签: php arrays wordpress associative-array