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?
It’s actually returning a value of
Trueforarray_walk_recursive. If you look at the function’s documentation, you’ll see that what this method is doing is calling the function_outputfor 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:
Where
_outputis called because that is the stringified name that you gave in thearray_walk_recursivefunction. 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 usearray_maplike this:Ultimately, if the recursion is something that you desire, you could probably do something like this:
That would return another array like $obj, but with whatever the callback was supposed to do.