如果你想在特定的位置從陣列中刪除一個項目,你可以得到該位置上的鍵,然後取消它:
$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);
的[從由密鑰數組中刪除線]可能重複(HTTP://計算器.com/questions/1782041/remove-line-by-array-by-key) – hakre