Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中递归修改数组_Php_Arrays_Recursion_Pass By Reference - Fatal编程技术网

在PHP中递归修改数组

在PHP中递归修改数组,php,arrays,recursion,pass-by-reference,Php,Arrays,Recursion,Pass By Reference,我试图修改PHP5函数中的数组 输入示例: 预期产出: 我编写了以下代码来将空对象(stdClass::uu set_state(array())对象)替换为null。该方法工作正常(我使用了一些调试日志进行检查),但是我给它的数组没有改变 private function replaceEmptyObjectsWithNull(&$argument){ if (is_array($argument)){ foreach ($argument as $innerA

我试图修改PHP5函数中的数组

输入示例:

预期产出:

我编写了以下代码来将空对象(stdClass::uu set_state(array())对象)替换为null。该方法工作正常(我使用了一些调试日志进行检查),但是我给它的数组没有改变

private function replaceEmptyObjectsWithNull(&$argument){
    if (is_array($argument)){
        foreach ($argument as $innerArgument) {
            $this->replaceEmptyObjectsWithNull($innerArgument);
        }
    } else if (is_object($argument)){
        if (empty((array) $argument)) {
            // If object is an empty object, make it null.
            $argument = null;
            \Log::debug("Changed an empty object to null"); // Is printed many times, as expected.
            \Log::debug($argument); // Prints an empty line, as expected.
        } else {
            foreach ($argument as $innerArgument) {
                $this->replaceEmptyObjectsWithNull($innerArgument);
            }
        }
    }
}
我这样称呼这个方法:

$this->replaceEmptyObjectsWithNull($myArray);
\Log::debug($myArray); // myArray should be modified, but it's not.

我做错了什么?我正在通过引用解析参数,对吗?

有一种非常简单的方法

您只需更改foreach循环以引用变量,而不必使用变量的副本。您可以使用
$innerArgument
前面的符号和符号执行此操作

foreach ($argument as &$innerArgument) {
    $this->replaceEmptyObjectsWithNull($innerArgument);
} 
注意循环中
$innerArgument
前面的
&
符号


你可以了解更多有关这方面的信息。您还可以了解有关一般参考的更多信息。

有一种非常简单的方法可以做到这一点

您只需更改foreach循环以引用变量,而不必使用变量的副本。您可以使用
$innerArgument
前面的符号和符号执行此操作

foreach ($argument as &$innerArgument) {
    $this->replaceEmptyObjectsWithNull($innerArgument);
} 
注意循环中
$innerArgument
前面的
&
符号


你可以了解更多有关这方面的信息。您还可以了解有关一般引用的更多信息。

foreach($argumentas$innerArgument)
更改为
foreach($argumentas&$innerArgument)
。这样,
$innerArgument
是一个参考,而不是副本。谢谢!这正是我需要的,太棒了!将
foreach($argumentas$innerArgument)
更改为
foreach($argumentas&$innerArgument)
。这样,
$innerArgument
是一个参考,而不是副本。谢谢!这正是我需要的,太棒了!
foreach ($argument as &$innerArgument) {
    $this->replaceEmptyObjectsWithNull($innerArgument);
}