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


unset an array with a specfic condition

基本上我有这个数组$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
        )

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

不带正则表达式:

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

使用regex(需要使用锚点):

$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]);
}

如果我理解,你试图只删除希腊,它应该很简单:

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

您正在使用的正则表达式将删除该键的值为0的每个国家,这也将在您的示例中排除502。