如果你想从数组中的特定位置移除一个项目,你可以获取该位置的键,然后取消设置:
$b = array(123,456,789,123);
$p = 2;
$a = array_keys($b);
if ($p < 0 || $p >= count($a))
{
throw new RuntimeException(sprintf('Position %d does not exists.', $p));
}
$k = $a[$p-1];
unset($b[$k]);
这适用于任何 PHP 数组,无论索引从哪里开始或字符串是否用于键。
如果您想对剩余的数组重新编号,只需使用array_values:
$b = array_values($b);
这将为您提供一个从零开始的数字索引数组。
如果原始数组也是从零开始的数字索引数组(如您的问题),您可以跳过有关获取密钥的部分:
$b = array(123,456,789,123);
$p = 2;
if ($p < 0 || $p >= count($b))
{
throw new RuntimeException(sprintf('Position %d does not exists.', $p));
}
unset($b[$p-1]);
$b = array_values($b);
或者直接使用array_splice处理偏移量而不是键并且重新索引数组(输入中的数字键不保留):
$b = array(123,456,789,123);
$p = 2;
if ($p < 0 || $p >= count($b))
{
throw new RuntimeException(sprintf('Position %d does not exists.', $p));
}
array_splice($b, $p-1, 1);