Reputation: 10288
I want to apply a function to each element/prop of an object but it seems array_walk_recursive()
does not work on object. i.e:
if( $re = $con->query("SELECT id, created_date, contents FROM " .
POST_DATA . " WHERE type = 'news' ORDER BY ".
"created_date DESC LIMIT $amount") ) {
if( $re->num_rows != 0 ) {
while( $ob = $re->fetch_object() ) {
$ob = array_walk_recursive( $ob, "_output" );
print_r($ob);
die();
}
}
}
would simply return '1'.
How might I resolve this?
Upvotes: 0
Views: 1570
Reputation: 1154
It's actually returning a value of True
for array_walk_recursive
. If you look at the function's documentation, you'll see that what this method is doing is calling the function _output
for each item and key in the object.
You should also have some code that looks similar to this, I would imagine, to get it to work correctly:
function _output($data, $key) {
echo "For the key $key, I got the data: ";
print_r($data);
}
Where _output
is called because that is the stringified name that you gave in the array_walk_recursive
function. That should print your values to the screen.
Edit:
It seems that I'm not actually answering what you were originally wanting to do, though. If you're wanting to apply a function to every element of an array, I would suggest that you look at array_map
. You can use array_map
like this:
function double($item) {
return 2 * $item;
}
array_map('double', $item);
Ultimately, if the recursion is something that you desire, you could probably do something like this:
function callback($key, $value) {
// do some stuff
}
function array_map_recursive($callback, $array) {
$new_array = array()
foreach($array as $key => $value) {
if (is_array($value)) {
$new_array[$key] = array_map_recursive($callback, $value);
} else {
$new_array[$key] = call_user_func($callback, $key, $value);
}
}
return $new_array;
}
array_map_recursive('callback', $obj);
That would return another array like $obj, but with whatever the callback was supposed to do.
Upvotes: 1