如何使用一个变量在PHP中过滤这样的数组?

时间:2013-02-06 10:35:54

标签: php arrays variables filter

我正在尝试用PHP过滤数组。请看我的阵列:

Array
(
    [0] => Array
        (
            [date_start_month_name] => January
            [approved] => Accepted: yes
        )

    [1] => Array
        (
            [date_start_month_name] => March
            [approved] => Accepted: yes
        )

    [2] => Array
        (
            [date_start_month_name] => March
            [approved] => Accepted: yes
        )

    [3] => Array
        (
            [date_start_month_name] => April
            [approved] => Accepted: yes
        )
)

我想使用月份名称过滤数组,例如: March ,并获得以下内容:

Array
(
    [0] => Array
        (
            [date_start_month_name] => March
            [approved] => Accepted: yes
        )

    [1] => Array
        (
            [date_start_month_name] => March
            [approved] => Accepted: yes
        )
)

我该怎么做?在此先感谢您的帮助。最好!

2 个答案:

答案 0 :(得分:2)

$march = array_filter($my_arr, function($value) { 
   return $value['date_start_month_name'] == "March"; 
});

答案 1 :(得分:1)

尝试array_filter

$array=array(array("month"=>"January","foo"=>"bar"),array("month"=>"January","foo"=>"bar"),array("month"=>"March","foo"=>"bar"),array("month"=>"March","foo"=>"bar"));
print_r($array);
$result=array_filter($array,function($o){return $o["month"]=="March";});
print_r($result);

输出:

Array
(
    [0] => Array
        (
            [month] => January
            [foo] => bar
        )

    [1] => Array
        (
            [month] => January
            [foo] => bar
        )

    [2] => Array
        (
            [month] => March
            [foo] => bar
        )

    [3] => Array
        (
            [month] => March
            [foo] => bar
        )

)
Array
(
    [2] => Array
        (
            [month] => March
            [foo] => bar
        )

    [3] => Array
        (
            [month] => March
            [foo] => bar
        )

)