John Davidson

Iterating over multidimensional PHP Object and changin values by reference

0 comments
Message:


I am trying to iterate over a php object and changing each string value by reference, but something is just not working. In some arrays the strings will not be changed. Anyone has an idea why? Or has a suggestion on how to solve the task?


Here is my code:



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);
}

Thank you very much!



My Answer:
$key => $value) {
if (is_string($value)) {
$object->$key = "changed";
} elseif (is_object($value)) {
recursive_object_string_changer($value);
}
}
}

This code should recursively iterate over the object and change any string values to "changed". Make sure to pass the object by reference to the function if you want the changes to be reflected outside of the function. You can do this by adding an ampersand before the parameter in the function definition:

function recursive_object_string_changer(&$object) {
// function body remains the same
}

This should solve the issue of some strings not being changed in the arrays.

Rate this post

4 of 5 based on 2101 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us