我想使用循环在任意位置向数组中添加一个元素
我有一个固定的队伍如下
$ranks=array("10","9","8","7","6","5","4","3","2","1");
我有一个根据链子随机排列的位置,
$agent_ranks=array("10","6","2","1");
缺少索引
我已经计算出了数组之间的差异
$arr_diff=array("9","8","7","5","4","3");
现在我想要一个动态数组作为结果:
$arr_diff_new=array("0","9","8","7","0","5","4","3","0","0");
如何在缺少的索引处添加
value="0"
? 最佳答案
您可以使用in_array
和for循环执行此操作:
$ranks=array("10","9","8","7","6","5","4","3","2","1");
$agent_ranks=array("10","6","2","1");
for($i=0;$i < count($ranks); $i++){
if(in_array($ranks[$i], $agent_ranks)){
$newarray[$i] = 0;
}else{
$newarray[$i] = $ranks[$i];
}
}
print_r($newarray);