将代码块转换为函数

时间:2015-06-19 13:40:38

标签: php mysql codeigniter php-5.3

我有几行代码:

        $array_to_filter // this array is unfiltered

   array_filter($array_to_filter, function($v){return array_filter($v) == array();});
    $c = function($v){
    return array_filter($v) != array();
    };
    $filtered_array = array_filter($airbnb, $c);


    print_r($filtered_array); // this is filtered array!

现在我将在我的代码中使用这段代码,我不想每次都重复它!我试过这样做:

    function filter_array ($tofilter, $filtered) {

    array_filter($tofilter, function($v){return array_filter($v) == array();});
    $c = function($v){
    return array_filter($v) != array();
    };
    $filtered = array_filter($filtered, $c); 
    return $filtered;
}

并像这样调用:filter_array($ array_to_filter,$ filtered_array);

没有运气..我做错了什么?

我要过滤的数组:

    [0] => Array
    (
        [RES_ID] => 2927135
        [CONFIRMATION] =>  QBMNMA
        [AIRBNB_AGENCY_INCOME] =>  €497
        [AIRBNB_INCOME] =>  €516

        [AIRBNB_FEES] =>  -€19

        [AIRBNB_PER_NIGHT] =>  €129
    )

[1] => Array
    (
        [RES_ID] => 
        [CONFIRMATION] => 
        [AIRBNB_AGENCY_INCOME] => 
        [AIRBNB_INCOME] => 
        [AIRBNB_FEES] => 
        [AIRBNB_PER_NIGHT] => 
    )

通过代码块的结果:

 [0] => Array
    (
        [RES_ID] => 2927135
        [CONFIRMATION] =>  QBMNMA
        [AIRBNB_AGENCY_INCOME] =>  €497
        [AIRBNB_INCOME] =>  €516

        [AIRBNB_FEES] =>  -€19

        [AIRBNB_PER_NIGHT] =>  €129
    )

通过函数的结果:

<p>Severity: Warning</p>
<p>Message:  array_filter() expects parameter 1 to be array, null given</p>
<p>Filename: controllers/Welcome.php</p>
<p>Line Number: 456</p>

1 个答案:

答案 0 :(得分:1)

  

我有一个关联数组,但有些数组是空的!例如,[RES_ID] =&gt;我想摆脱整个阵列而不仅仅是关键。这就是它的作用 - 瓦列里5分钟前

function filter_array ($to_filter)
{
    foreach ($to_filter as $index => $child_array)
    {
        if (!array_filter($child_array)) {
            // all keys are empty.
            unset($to_filter[$index]);
        }
    }

return $to_filter;
}

$filtered_array = filter_array($array_to_filter);

这会有用吗?