在 PHP 中递归修改数组

Modify array recursively in PHP

我正在尝试修改 PHP 5 函数中的数组。

Example input:

array('name' => 'somename', 'products' => stdClass::__set_state(array()))

Expected output:

array('name' => 'somename', 'products' => null)

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

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 前面的 & 符号。

您可以了解更多相关信息in the PHP docs. You can also learn more about references in general in the PHP docs