我正在嘗試遍歷一個 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);
}
非常感謝!
uj5u.com熱心網友回復:
我認為您想讓函式的簽名也接受初始物件作為參考,以便遞回適用于后續呼叫。
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是一個陣列或一個物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315804.html
下一篇:從陣列物件的鍵創建一個新陣列
