按特定键的值过滤2D数组

时间:2009-10-20 12:02:26

标签: php arrays filter

如何过滤此数组以仅保留[category] => 1的项目?

[0] => Array
    (
        [link] => index
        [image] => spot
        [category] => 0
    )

[1] => Array
    (
        [link] => test
        [image] => spotless
        [category] => 0
    )

[2] => Array
    (
        [link] => differentcat
        [image] => spotly
        [category] => 1
    )

4 个答案:

答案 0 :(得分:6)

使用array_filter

你想要这样的东西(假设你要保留category 1)的条目:

function categoryone($var)
{
    return (is_array($var) && $var['category'] == 1);
}

print_r(array_filter($your_array, "categoryone"));

答案 1 :(得分:2)

您可以使用array_filter检查回调中的类别值。 http://php.net/manual/en/function.array-filter.php

答案 2 :(得分:2)

定义一个这样的过滤函数:

function filter_function($var) {
    return is_array($var) && $var['category'] == 1;
}

...然后使用array_filter()将此函数应用于您的数组:

$filtered_array = array_filter($my_array, 'filter_function');

编辑:更改过滤功能以保持匹配值而不是丢弃它们。

答案 3 :(得分:0)

@pathros:

要使用不同的值进行过滤,解决方案如下:(测试:-))

//Define your array
$my_array = array(
  0 =>   array(
    'cat' =>         '1',
    'value' =>         'Value A'
    )
  ,
  1 =>   array(
    'cat' =>         '2',
    'value' =>         'Value B'
    )
  ,
  2 =>   array(
    'cat' =>         '0',
    'value' =>         'Value C'
    )
  ,
  3 =>   array(
    'cat' =>         '1',
    'value' =>         'Value D'
    )
  );

//Define your filtering function
function my_filtering_function($in_array) {
    return is_array($in_array) && $in_array['cat'] == $GLOBALS['filter_param_1'];
}

//TEST #1 : Set the desired value to 2
$GLOBALS['filter_param_1'] = 2;
//Filter your array to only return items that match "cat=2"
$filtered_array = array_filter($my_array, 'my_filtering_function');
e('Number of matching records : '.count($filtered_array)).'record(s)<br>'; //Will return "1 record(s)" (the second record of your array)

//TEST #2 : Set the desired value to 1
$GLOBALS['filter_param_1'] = 1;
//Filter your array to only return items that match "cat=1"
$filtered_array = array_filter($my_array, 'my_filtering_function');
e('Number of matching records : '.count($filtered_array)).'record(s)<br>'; //Will return "2 record(s)" (the first and the last of your array)