我正在尝试修改PHP 5函数中的数组。
示例输入:
array('name' => 'somename', 'products' => stdClass::__set_state(array()))
预期产出:
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.
我在这里做错了什么?我正在通过引用解析参数,对吧?
答案 0 :(得分:2)
有一种非常简单的方法可以做到这一点。
您只需更改foreach循环以引用变量,不使用变量副本。您可以使用$innerArgument
前面的符号符号来执行此操作。
foreach ($argument as &$innerArgument) {
$this->replaceEmptyObjectsWithNull($innerArgument);
}
注意循环中&
前面的$innerArgument
符号。
您可以详细了解此in the PHP docs。您还可以了解有关参考文献in the PHP docs的更多信息。