如何在 PHP 中的多维数组中按 key=>value 进行搜索

问题描述:

是否有任何快速方法可以获取在多维数组中找到键值对的所有子数组?我不能说阵列会有多深.

Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can't say how deep the array will be.

简单示例数组:

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1")
);

当我搜索 key=name 和 value="cat 1" 时,函数应该返回:

When I search for key=name and value="cat 1" the function should return:

array(0 => array(id=>1,name=>"cat 1"),
      1 => array(id=>3,name=>"cat 1")
);

我猜这个函数必须是递归的才能深入到最深层次.

I guess the function has to be recursive to get down to the deepest level.

代码:

function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => cat 1
        )

    [1] => Array
        (
            [id] => 3
            [name] => cat 1
        )

)

如果效率很重要,您可以编写它,以便所有递归调用将其结果存储在同一个临时 $results 数组中,而不是将数组合并在一起,如下所示:

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results array rather than merging arrays together, like so:

function search($array, $key, $value)
{
    $results = array();
    search_r($array, $key, $value, $results);
    return $results;
}

function search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[$key] == $value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        search_r($subarray, $key, $value, $results);
    }
}

关键在于 search_r 通过引用而不是通过值来获取它的第四个参数;&符号 & 至关重要.

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

仅供参考:如果您使用的是旧版本的 PHP,那么您必须在对 search_r调用中而不是在其声明中指定传递引用部分.也就是说,最后一行变成了search_r($subarray, $key, $value, &$results).

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results).