从另一个数组的值取消设置数组索引?

时间:2013-12-10 03:34:36

标签: php

我想在php中使用unset取消设置数组索引。

<?php
$a=array('a','b','c','d','e');
$b=array(2,3);//2,3 are indexs which I have to unset from array a.
print_r($a);
unset($a,$b);//how can I do it.
print_r($a);
?>

我希望输出如下:迭代超过$ b并取消设置($ a [$ value]);

Array ( [0] => a [1] => b [2] => c [3] => d [4] => e ) 
Array ([0] => a [1] => b [4] => e ) 

3 个答案:

答案 0 :(得分:2)

如果您正在寻找oneline解决方案,请尝试以下方法:

$a = array_diff_key($a, array_flip($b));

我也为此算法编写了性能测试(source)。它比
foreach($b as $val) unset($a[$val]); 20-30%。

<强>更新

似乎此算法具有来自数据量的非线性性能依赖性:

$a包含1000个元素:

Test name       Repeats         Result          Performance     
array_diff_key  10000           0.990571 sec    +0.00%
foreach         10000           1.183903 sec    -19.52%
带有10000个元素的

$a

Test name       Repeats         Result          Performance     
foreach         10000           12.924521 sec   +0.00%
array_diff_key  10000           28.338741 sec   -119.26%

$a,结果为100000个元素:

Test name       Repeats         Result          Performance     
foreach         10000           201.961125 sec  +0.00%
array_diff_key  10000           619.329440 sec  -206.66%

如果$a数组的元素超过1000个,我希望foreach算法。

答案 1 :(得分:0)

array_diff_key

<?php
$a=array('a','b','c','d','e');
$b=array(0,1);//0,1 are indexs which I have to unset from array a.
print_r($a);
$a = array_diff_key ($a,$b);//how can I do it.
print_r($a);
?>

答案 2 :(得分:0)

$a=array('a','b','c','d','e');
$b=array(2,3);//2,3 are indexs which I have to unset from array a.
print_r($a);
$c = removeFromAnotherArray($a,$b);
print_r($c);
function removeFromAnotherArray($a,$b)
{
    foreach($b as $key=>$val)
    {
        if(array_key_exists($key,$a))
        {
            unset($a[$val]);
        }
    }
    return $a;
}

输出将是:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)
Array
(
    [0] => a
    [1] => b
    [4] => e
)