在函数名称中使用引用运算符返回通知

时间:2015-07-22 08:29:26

标签: php recursion reference

我的功能:

function &get_element_from_array(&$array, $searchValue){    

    foreach($array as $id => &$subtree) {
        if ($id === $searchValue) {
            return $subtree;
        }

        if (isset($subtree['children'])) {
            $subsearch = &$this->get_element_from_array($subtree['children'], $searchValue);

            if ($subsearch !== false) {
                return $subsearch;
            }
        }
    }

    return false;
}

我有一个这样的数组:

$table = [
1 => [
    'id' => 1,
    'children_count' => 0,
    'visited' => 1,
    'children_visited' => 0
],
2 => [
    'id' => 2,
    'children_count' => 0,
    'visited' => 1,
    'children_visited' => 0,
    'children' => [
        3 => [
            'id' => 3,
            'children_count' => 0,
            'visited' => 1,
            'children_visited' => 0,
            'children' => [
                4 => [
                    'id' => 4,
                    'children_count' => 0,
                    'visited' => 1,
                    'children_visited' => 0,
                    'children' => [
                        5 => [
                            'id' => 5,
                            'children_count' => 0
                            'visited' => 0,
                            'children_visited' => 0
                        ],

                        6 => [
                            'id' => 6,
                            'children_count' => 0
                            'visited' => 1,
                            'children_visited' => 0
                        ]
                    ]
                ]
            ]
        ]
    ]
]

];

此功能按预期工作。问题是,它通知我:

  

消息:只能通过引用

返回变量引用

问题在于函数名称中的引用运算符。 如果我删除&amp ;.函数不能按预期工作。通知停止:)

我在完成此功能后将一些数据发送回POST调用,所有这些通知都会发送回javascript :(

你会窥视什么样的解决方案?

1 个答案:

答案 0 :(得分:1)

解决方案是始终返回变量。

function &get_element_from_array(&$array, $searchValue){    

    $result = false;

    foreach($array as $id => &$subtree) {
        if ($id === $searchValue) {
            return $subtree;
        }

        if (isset($subtree['children'])) {
            $subsearch = &$this->get_element_from_array($subtree['children'], $searchValue);

            if ($subsearch !== false) {
                return $subsearch;
            }
        }
    }

    return $result;
}