php数组基于值删除n个项目

时间:2018-12-26 13:28:56

标签: php arrays

我有这个数组,有4个值= 3,我如何只删除其中两个?

Array ( 
    [0] => 1 
    [1] => 2 
    [2] => 1 
    [3] => 2
    [4] => 3
    [5] => 3
    [6] => 3 
    [7] => 2
    [8] => 2
    [9] => 2
    [10] => 1
    [11] => 2
    [12] => 3
    [13] => 2 
)

我已经尝试过unset()。有什么办法可以做到这一点?

所以数组看起来像这样

Array ( 
    [0] => 1
    [1] => 2
    [2] => 1
    [3] => 2
    [4] => 3 
    [5] => 3
    [6] => 2
    [7] => 2 
    [8] => 2 
    [9] => 1
    [10] => 2
    [11] => 2 
)

2 个答案:

答案 0 :(得分:2)

只需使用unsetarray_search进行两次呼叫:

$array = array(1,2,3,3,3,4,5,6);
print_r($array);
unset($array[array_search(3, $array)]);
unset($array[array_search(3, $array)]);
print_r($array);

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 3
    [4] => 3
    [5] => 4
    [6] => 5
    [7] => 6
)

Array
(
    [0] => 1
    [1] => 2
    [4] => 3
    [5] => 4
    [6] => 5
    [7] => 6
)

但这假设您对array_search的行为感到满意,该行为将返回与值3匹配的 first 索引。如果您有其他删除顺序,然后声明它,然后可能需要更改代码。

答案 1 :(得分:1)

您可以使用循环,并在遇到3时跳过前两次。然后,对于下一个匹配项,可以使用unset。然后,您可以使用array_values重置密钥:

$items = [
    1,2,1,2,3,3,3,2,2,2,1,2,3,2
];

$found  = 0;
foreach ($items as $key => $item) {
    if ($item === 3) {
        if ($found < 2) {
            $found++;
            continue;
        }
        unset($items[$key]);
    }
}
print_r(array_values($items));

结果

Array
(
    [0] => 1
    [1] => 2
    [2] => 1
    [3] => 2
    [4] => 3
    [5] => 3
    [6] => 2
    [7] => 2
    [8] => 2
    [9] => 1
    [10] => 2
    [11] => 2
)

Php demo