我有一个递归函数,用全局变量解析一个对象/数组.如果我注释掉全局变量,我什么也得不到,但如果我把它留在其中,则不断向数组中添加应该在其自己的结果集中的其他值.我需要在这里换一些东西吗?
更新#2:我怎样才能获得我想要的回报,我以为我正在将所有唯一值推送到数组中?
function getResp($objectPassed) {
foreach($objectPassed as $element) {
if(is_object($element)) {
// recursive call
$in_arr = getResp($element);
}elseif(is_array($element)) {
$in_arr = getResp($element);
} else {
// XML is being passed, need to strip it
$element = strip_tags($element);
// Trim whitespace
$element = trim($element);
// Push to array
if($element != '') {
if (!preg_match("/^[0-9]$/", $element)) {
if (!in_array($element,$in_arr)) {
$in_arr[] = $element;
}
}
}
}
}
return $in_arr;
}
Run Code Online (Sandbox Code Playgroud)
INPUT:
stdClass Object
(
[done] => 1
[queryLocator] =>
[records] => Array
(
[0] => stdClass Object
(
[type] => typeName
[Id] => Array
(
[0] => a0E50000002jxhmEAA
[1] => a0E50000002jxhmEAA
)
)
[1] => stdClass Object
(
[type] => typeName
[Id] => Array
(
[0] => a0E50000002jxYkEAI
[1] => a0E50000002jxYkEAI
)
)
)
[size] => 2
)
Run Code Online (Sandbox Code Playgroud)
返回:
Array
(
[0] => a0E50000002jxYkEAI
)
Run Code Online (Sandbox Code Playgroud)
想要回归:
Array
(
[0] => a0E50000002jxYkEAI
[1] => a0E50000002jxhmEAA
)
Run Code Online (Sandbox Code Playgroud)
是必要的全局变量吗?否则你可以这样简化它:
function getResp($objectPassed, &$in_arr = array()) { // <-- note the reference '&'
foreach($objectPassed as $element) {
if(is_object($element) || is_array($element)) { // <-- else if statement simplified
getResp($element,$in_arr);
} else {
// XML is being passed, need to strip it
$element = strip_tags($element);
// Trim whitespace
$element = trim($element);
// Push to array
if($element != '' && // <-- everything in one test
!preg_match("/^[0-9]$/", $element) &&
!in_array($element,$in_arr))
{
$in_arr[] = $element;
}
}
}
return $in_arr;
}
Run Code Online (Sandbox Code Playgroud)
然后你做:
$result = getResp($data);
Run Code Online (Sandbox Code Playgroud)
如果递归函数必须一遍又一遍地访问相同的资源(在这种情况下是初始数组),我总是将其作为引用传递.
我不知道是否可以测量,但我猜这比复制值更有效.