且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中的多维数组的价值;如何通过key =&GT搜索

更新时间:2023-01-16 20:20:00

code:

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
        )

)

如果效率是很重要的,你可以写,这样所有的递归调用存储他们的结果在同一临时 $结果阵列,而不是合并数组在一起,就像这样:

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.

FYI:如果你有PHP的是旧版本,那么你必须指定在通通过引用部分的呼叫 search_r 而不是在它的声明。也就是说,最后一行变成 search_r($子数组$键,$值,和放大器; $结果)。

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).