取消设置具有特定条件的数组

时间:2014-04-14 16:41:40

标签: php arrays

基本上我有这个数组$code

Array
(
    [1] => Array
        (
            [0] => FRANCE
            [1] => 26422
            [2] => 61748
            [3] => 698477678
        )

    [2] => Array
        (
            [0] => UNITED STATES
            [1] => 545
            [2] => 2648
            [3] => 55697455
        )

    [3] => Array
        (
            [0] => CANADA
            [1] => 502
            [2] => 1636
            [3] => 15100396
        )
    [4] => Array
        (
            [0] => GREECE
            [1] => 0
            [2] => 45
            [3] => 458
        )

我想用$code[$key][1] == 0取消设置所有国家/地区,所以我厌倦了这个:

$code = array_filter($code, function (array $element) {
return !preg_match('(0)i', $element[1]);
});

但它会返回所有国家/地区,除非$code[$key][1] 0中有一个国家/地区,如下所示:

Array
(
    [1] => Array
        (
            [0] => FRANCE
            [1] => 26422
            [2] => 61748
            [3] => 698477678
        )

    [2] => Array
        (
            [0] => UNITED STATES
            [1] => 545
            [2] => 2648
            [3] => 55697455
        )

我怎么能做到这一点?谢谢!

2 个答案:

答案 0 :(得分:2)

没有正则表达式:

$code = array_filter($code, function (array $element) {
return ($element[1] !== 0);
});

使用正则表达式(您需要使用anchors):

$code = array_filter($code, function (array $element) {
return !preg_match('/^0$/', $element[1]);
});

但是,我建议使用简单的foreach循环代替array_filter

foreach($code as $key => $val){
    if($val[1] === 0) unset($code[$key]);
}

答案 1 :(得分:1)

如果我理解,你试图只删除希腊,那应该是这样简单:

$code = array_filter($code, function (array $element) {
    return $element[1] != 0
});

您正在使用的正则表达式将删除键中值为0的每个国家/地区,在您的示例中也会排除502.