PHP - 搜索多维数组并返回对结果的引用
PHP - Searching a multidimensional array and returning a reference to the result
我正在尝试编写一个函数,在多维数组中搜索具有特定 ID 的数组,然后 returns 找到该数组的引用。
我想到了这个,但它没有像我预期的那样工作。
$list = array(
"id"=>"123",
"items"=>array(
"id"=>"456"
)
);
function &getArrayById(&$array, $id) {
//Found
if(isset($array["id"]) && $array["id"] == $id) {
return $array;
}
//Not found, looking for nested array
foreach(array_keys($array) as $key) {
if (gettype($array[$key]) === "array") {
$o = getArrayById($array[$key], $id);
if(gettype($o) != "NULL") {
return $o;
}
}
}
//Not found - end
return null;
}
$a =& getArrayById($list, "456");
$a["id"] = "ID EDITED";
echo $list["items"]["id"]; //"456" - not "ID EDITED" like I want
我注意到的一件事是,当我使用 123 的 ID(即数组的最顶层)进行搜索时,尝试使用 $a 编辑返回的数组的 ID 按预期工作,所以我想知道是否是递归没有像我预期的那样工作。
确实,递归调用还需要 "assignment by reference" ( =&
):
$o =& getArrayById($array[$key], $id);
它是 PHP 中的其中之一...在函数定义中有 &
前缀本身是不够的,如 the documentation 中所述:
Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done
我正在尝试编写一个函数,在多维数组中搜索具有特定 ID 的数组,然后 returns 找到该数组的引用。 我想到了这个,但它没有像我预期的那样工作。
$list = array(
"id"=>"123",
"items"=>array(
"id"=>"456"
)
);
function &getArrayById(&$array, $id) {
//Found
if(isset($array["id"]) && $array["id"] == $id) {
return $array;
}
//Not found, looking for nested array
foreach(array_keys($array) as $key) {
if (gettype($array[$key]) === "array") {
$o = getArrayById($array[$key], $id);
if(gettype($o) != "NULL") {
return $o;
}
}
}
//Not found - end
return null;
}
$a =& getArrayById($list, "456");
$a["id"] = "ID EDITED";
echo $list["items"]["id"]; //"456" - not "ID EDITED" like I want
我注意到的一件事是,当我使用 123 的 ID(即数组的最顶层)进行搜索时,尝试使用 $a 编辑返回的数组的 ID 按预期工作,所以我想知道是否是递归没有像我预期的那样工作。
确实,递归调用还需要 "assignment by reference" ( =&
):
$o =& getArrayById($array[$key], $id);
它是 PHP 中的其中之一...在函数定义中有 &
前缀本身是不够的,如 the documentation 中所述:
Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done