过滤多维数组而不影响密钥

时间:2015-11-05 07:55:29

标签: php arrays multidimensional-array filter

我正在开发一个自定义PHP项目,我需要获取多维数组的子集。

我有一个数组

Array
(
    [0] => Array
        (
            [0] => 2011
            [1] => Allegany
            [2] => 55.4
        )

    [1] => Array
        (
            [0] => 2012
            [1] => Albany
            [2] => 325.1
        )

    [2] => Array
        (
            [0] => 2011
            [1] => Bronx
            [2] => 11
        )
    [3] => Array
        (
            [0] => 2012
            [1] => Bronx
            [2] => 11
        )
)

我想返回一个 [0] =>的数组2012 出现,如下所示

Array
(


    [1] => Array
        (
            [0] => 2012
            [1] => Albany
            [2] => 325.1
        )


    [3] => Array
        (
            [0] => 2012
            [1] => Bronx
            [2] => 11
        )
)

1 个答案:

答案 0 :(得分:2)

编写array_filter()函数以允许您根据可自定义的条件从数组中选择条目的子集

$searchColumn = 0;
$searchValue = 2012;

$subset = array_filter(
    $originalArray,
    function($value) use ($searchColumn, $searchValue) {
        return isset($value[$searchColumn]) && $value[$searchColumn] == $searchValue;
    }
);

或更通用的变体:

$searchCriteria = [0 => 2012, 2 => 11];

$subset = array_filter(
    $originalArray,
    function($value) use ($searchCriteria) {
        return count($searchCriteria) == count(array_intersect_assoc($value, $searchCriteria));
    }
);

修改

Variant以简化在不同列中搜索匹配

Artistname =input("Enter artist name: ")