PHP ArrayObject / ArrayIterator: Concept with Example

I am trying to understand the concept of an array of objects in PHP. In the update, I just used regular arrays to view a list of entries and display them in the say table.

I know that I can do this with Object, but I'm not quite sure how to do this.

I understand the concept of a single instance of an object with all properties representing fields with associated values ​​populated from the database, which can be called as:

$objUser->first_name; 

Now, what I would like to understand, and simply cannot find a simple answer, is how to allow a list of users that I would like to display on one page. I saw that there are ArrayObject, ArrayIterator, etc., but I just can’t understand how they work, so if someone tries to explain this with a few examples of how this can be done, this would be very appreciated.

What I'm looking for is an object containing a list of elements that I can skip this way (if at all possible):

 foreach($objUsers as $objUser) { echo $objUser->first_name; } 

Thanks.

+7
php foreach arrayobject arrayiterator
source share
2 answers

It is possible. Paste your object into the Iterator interface, and then you can foreach on it. (Note: you need to correctly implement methods to advance and rewind your array)

Additional Information:

+4
source share

If I have reached this problem, you ask how to work with many objects?

So, if you use an array of objects, for example, from ORM.

 $users_list = new Users(); $arr_users = $users_list->all(); 

In $ arr_users you will have an array with many user objects from your database. Each object has some properties, for example: id, name, gender and age.

 foreach($arr_users as $single_user) { echo $single_user->id; echo $single_user->name; echo $single_user->gender; echo $single_user->age; } 

If you need only one user:

 echo $arr_users[1]->name; 

You can also work with an array of such objects. First, created a new array from $ arr_users;

 foreach($arr_users as $single_user){ $arr_user_by_id[$single_user->id] = $single_user; } 

Now you have a new array, where the keys are the user ID and the user of the value object.

Thus, you can get information about the user by his identifier.

 echo $arr_users[$_GET['uid']]->name; 

Hope I could help to understand a little.

+1
source share

All Articles