PHP按特定键过滤2维数组

时间:2011-09-07 22:01:15

标签: php multidimensional-array filtering

我有这个数组:

Array
(
    [702a4584] => Array
        (
            [type] => folder
            [id] => 702a4584
        )

    [b547b3a9] => Array
        (
            [type] => folder
            [id] => b547b3a9

        )

    [fcb0d055] => Array
        (
            [type] => page
            [id] => fcb0d055
        )
)

我想过滤数组,只保留“folder”类型:

Array
(
    [702a4584] => Array
        (
            [type] => folder
            [id] => 702a4584
        )

    [b547b3a9] => Array
        (
            [type] => folder
            [id] => b547b3a9

        )

)

我可以这样做,但我需要一个通用功能:

$temp = array();
foreach($array as $key => $value)
{
    if($value['type'] =="folder")
    {
        $temp[$key] = $value; 
    }
}

2 个答案:

答案 0 :(得分:19)

您可以使用array_filter

$filtered = array_filter($array, function($v) { return $v['type'] == 'folder'; });

答案 1 :(得分:0)

$input = Array(1,2,3,1,2,3,4,5,6);
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));