1 回答
TA贡献1825条经验 获得超6个赞
新答案。
我已经用你的新数组格式更新了我的答案。
这次我们创建了一个包含 50 个索引的数组,所有索引都设置为“-”。然后我们检查输出数组并将玩家姓名放在具有 50 个索引的数组中的正确位置。最后,我们检查 50 个索引并将它们打印到屏幕上。
这是代码:
<?php
$output= array(
array(
"player_number" => 1,
"player_name"=> "player1"
),
array(
"player_number" => 2,
"player_name"=> "player2"
),
array(
"player_number" => 3,
"player_name"=> "player3"
),
array(
"player_number" => 6,
"player_name"=> "player6"
),
array(
"player_number" => 8,
"player_name"=> "player8"
),
array(
"player_number" => 12,
"player_name"=> "player12"
),
);
$player_array = array();
// Create an array with 50 indexes all set to '-'
for($i=1; $i <= 50; $i++){ // loop for 50 times
$player_array[$i]= "-";
}
// update the player array with names;
foreach($output as $value){
$player_array[$value['player_number']] = $value['player_name'];
}
// print out numbers and names
foreach($player_array as $number => $name){
echo $number. " | ".$name."<br>";
}
旧答案
您必须创建一个运行 50 次的 for 循环,检查数组中的索引是否有值,以及该索引处是否有使用该名称。否则它只会使用 - 作为玩家名称。
尝试这个:
<?php
$my_array= array(
1 => "player1",
2 => "player2",
3 => "player3",
6 => "player6",
8 => "player8",
12 => "player12",
);
for($i=1; $i <= 50; $i++){ // loop for 50 times
$player_name = "-";
if(isset($my_array[$i])){ // if the player name is set, use it
$player_name = $my_array[$i];
}
echo $i. " | ".$player_name."<br>";
}
?>
查看isset()函数。
你也可以使用array_key_exists()代替 isset()。像这样:
for($i=1; $i <= 50; $i++){
$player_nick = "-";
if(array_key_exists($i,$my_array)){ //if value of $i is an index in the array
$player_nick = $my_array[$i];
}
echo $i. " | ".$player_name."<br>";
}
另请查看isset() 与 array_key_exists()。方便知道两者之间的区别。
- 1 回答
- 0 关注
- 120 浏览
添加回答
举报