在array_filter中的回调函数中获取false值

时间:2012-01-09 08:12:53

标签: php

我有一个这样的数组:

Array ( [PlasticContainmentTrained] => 0 [AvoidDustSpreadTrained] => 1 [PostRenCleaningTrained] => 0 [EntranceWarningSign] => 1 [IntObjectCovered] => 1 [IntHVAC] => 0 [IntWindowClosed] => 1 [ExtWindowClosed] => 0 [IntDoorClosed] => 1 [ExtDoorClosed] => 0 [DoorCovered] => 1 [IntFloorCovered] => 0 [ExtGroundCovered] => 1 [ExtVertContainment] => 0 [WasteContained] => 1 [AllChipsDebris] => 0 [WorkAreaSurface] => 0 [DustClearanceTesting] => 1 [WasteHandlingTrained] => 1 [MaintainContainmentTrained] => 0 [PostingWarningSignTrained] => 1 [DescriptionOfRenovation] => bnfdbndljnbljdfnbljkdnfljn [TrainedWorkers] => jvndfjnvdfvjndfljvndfljvn [DustSamplingTechnicanNames] => jvnfjdfnlvjdfjvndfljndflj [QualificationCopies] => dfjvdjf [KitUsed] => vjnjkdsfnvljdnvdjfvndfjbnjgbnndfn [TestLocations] => jdfjnvljndfvjdnfvjdnfvjkfnlj [CertifiedRenPerformed] => fdjndfljvndfljvndfjvndflk [ReportAttachPath] => undefined [IAccept] => undefined [ProjectId] => 1 ) 

我希望过滤此数组但只有'undefined'值不是'0'。我已经使用了array_filter()函数:

function filterValue($var)
        {

            if($var=='0')
            {
                return 0;
            }
            elseif($var!='undefined')
            {
                return $var;
            }
        }
        $this->data = array_filter($_POST, "filterValue");

但它也会过滤'0'值。我怎么能这样做。

请任何人帮助我......

2 个答案:

答案 0 :(得分:1)

那是因为'0'的计算结果为布尔值false。只检查undefined,如果未定义则返回false,如果不是,则返回true:

<?php
$data = array_filter( $data, function( $element ) {
  return $element !== 'undefined';
});

答案 1 :(得分:0)

您还可以像原始示例一样创建一个回调函数来重用,这有助于减少重复的代码。此自定义回调函数还会修剪空格,并允许您指定不希望过滤掉的值数组:

// Customized "array_filter" callback to preserve "0" in submitted values:
function empty_array_filter($val) {
    $val = trim($val);
    $allowed_vals = array('0'); // List of values to keep (e.g. these should not be treated as "false").
    return in_array($val, $allowed_vals, true) ? true : ( $val ? true : false );
}

然后将您的数组过滤器与您的自定义回调一起使用,如下所示:

// Use the custom callback instead of the default one:
$array_data = array_filter($array_data, 'empty_array_filter');