PHP: how can I sort and filter an "array", that is an Object, implementing ArrayAccess? -
i have object collection of objects, behaving array. it's database result object. following:
$users = user::get(); foreach ($users $user) echo $user->name . "\n";
the $users
variable object implements arrayaccess
, countable
interfaces.
i'd sort , filter "array", can't utilize array functions on it:
$users = user::get(); $users = array_filter($users, function($user) {return $user->source == "twitter";}); => warning: array_filter() expects parameter 1 array, object given
how can i sort , filter kind of object?
you can't. purpose of arrayaccess
interface not create oop wrapper arrays (although used such), allow array-like access collections might not know elements beginning. imagine web service client, calls remote procedure in offsetget()
, offsetset()
. can access arbitrary elements, cannot access whole collection - not part of arrayaccess
interface.
if object implements traversable
(via iterator
or iteratoraggregate
), array @ to the lowest degree constructed (iterator_to_array
job). still have convert that, native array functions only take arrays.
if object stores info internally array, efficient solution of course of study implement toarray()
method returns array (and maybe calls toarray()
recursively on contained objects).
php arrays spl arrayaccess countable
No comments:
Post a Comment