【问题标题】:Converting Block of code Into Function将代码块转换为函数
【发布时间】:2015-09-05 12:37:39
【问题描述】:

我有那几行代码:

        $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>

【问题讨论】:

  • 定义“没有任何运气”。它是如何失败的?
  • 嗯,使用了吗?你在哪里/如何使用它?当您调试它时,运行时值究竟在哪里出现了意外情况?
  • 仅供参考,您对array_filter 的第一次调用绝对没有任何作用。
  • 该功能应该做什么。用文字解释。
  • 我以为你要过滤的数组是$array_to_filter ...这太混乱了。

标签: php mysql codeigniter php-5.3


【解决方案1】:

我有一个关联数组,但有些数组是空的!例如,在 [RES_ID] => 里面,我想摆脱整个数组,而不仅仅是键。这就是它的作用——Valery 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);

这行得通吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2020-03-22
    相关资源
    最近更新 更多