PHP: how can I sort and filter the "array", that is, an object that implements ArrayAccess?

I have an object, which is a collection of objects that behave like an array. This is a database result object. Something like the following:

$users = User::get(); foreach ($users as $user) echo $user->name . "\n"; 

The $users variable is an object that implements ArrayAccess and Countable .

I would like to sort and filter this “array”, but I cannot use the array functions on it:

 $users = User::get(); $users = array_filter($users, function($user) {return $user->source == "Twitter";}); => Warning: array_filter() expects parameter 1 to be array, object given 

How can I sort and filter this kind of object?

+4
source share
2 answers

You can not. The purpose of the ArrayAccess interface is not only to create an OOP wrapper for arrays (although it is often used as such), but also to access collections like arrays that might not even know all their elements from the very beginning. Imagine a web service client that calls a remote procedure in offsetGet() and offsetSet() . You can access arbitrary elements, but you cannot access the entire collection - this is not part of the ArrayAccess interface.

If the object also implements Traversable (via Iterator or IteratorAggregate ), an array could be built from it ( iterator_to_array is doing the job). But you still need to convert it like this, the function’s own array only accepts arrays.

If your object stores data internally as an array, the most effective solution is, of course, to implement the toArray() method, which returns this array (and, possibly, recursively calls toArray() on the contained objects).

+8
source
0
source

All Articles