【问题标题】:Iterating over multidimensional PHP Object and changin values by reference通过引用迭代多维 PHP 对象和更改值
【发布时间】:2021-11-28 13:09:33
【问题描述】:

我正在尝试迭代一个 php 对象并通过引用更改每个字符串值,但有些东西不起作用。在某些数组中,字符串不会更改。任何人都知道为什么?或者对如何解决任务有建议?

这是我的代码:


recursive_object_string_changer($object);

function recursive_object_string_changer($object)
{
    if($object == null) {
        return;
    }
    foreach ($object as &$attribute) {
        if (is_string($attribute)) {
            $attribute = $attribute."!";
        } else if (is_array($attribute)) {
            recursive_object_string_changer($attribute);
        } else if (is_object($attribute)) {
            recursive_object_string_changer($attribute);
        }
    }
    unset($attribute);
}

非常感谢!

【问题讨论】:

  • 你能用stdClass做一个非常简单的示例对象供我们参考吗?

标签: php object reference iteration


【解决方案1】:

我认为您想让函数的签名也接受初始对象作为引用,以便递归在后续调用中起作用。

recursive_object_string_changer($object);

function recursive_object_string_changer(&$object)
{
    if ($object === null) {
        return;
    }
    foreach ($object as &$attribute) {
        if (is_string($attribute)) {
            $attribute .= "!";
        } elseif (is_array($attribute)) {
            recursive_object_string_changer($attribute);
        } elseif (is_object($attribute)) {
            recursive_object_string_changer($attribute);
        }
    }
    unset($attribute);
}

我用这个作为示例:

$object = new stdClass();
$object->string = 'Test';
$object->array = [
    'a',
    'b',
    'c',
];

$subObject = new stdClass();
$subObject->string = 'Another String';
$object->object = $subObject;

产生:

object(stdClass)#1 (3) {
  ["string"]=>
  string(5) "Test!"
  ["array"]=>
  array(3) {
    [0]=>
    string(2) "a!"
    [1]=>
    string(2) "b!"
    [2]=>
    string(2) "c!"
  }
  ["object"]=>
  object(stdClass)#2 (1) {
    ["string"]=>
    string(15) "Another String!"
  }
}

您可能总是希望在 for 循环之前添加一个保护,以确保 $object 首先是一个数组或一个对象。

【讨论】:

  • 现在可以使用了,非常感谢!!
猜你喜欢
  • 2013-06-10
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 2016-09-29
相关资源
最近更新 更多