如果您想从特定位置删除数组中的一个项目,可以获取该位置的键,然后取消设置它:
$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);