I have an array of objects; running print_r()
returns the output below;
Array ( [0] => stdClass Object ( [sm_id] => 1 [c_id] => 1 ) [1] => stdClass Object ( [sm_id] => 1 [c_id] => 2 ) )
How to loop through the result and access the student class objects?
PHP provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement.
Use the foreach($array_name as $element) to iterate over elements of an indexed array. Use the foreach($array_name as $key => $value) to iterate over elements of an associative array.
JavaScript's Array#forEach() function lets you iterate over an array, but not over an object.
The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of different datatype. The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.
Use
//$arr should be array as you mentioned as below foreach($arr as $key=>$value){ echo $value->sm_id; }
OR
//$arr should be array as you mentioned as below foreach($arr as $value){ echo $value->sm_id; }
Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach
loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:
foreach ($arr as $item) { echo $item->sm_id; }
In this example each of our values in the $arr
will be accessed in order as $item
. So we can print our values directly off of that. We could also include the index if we wanted:
foreach ($arr as $index => $item) { echo "Item at index {$index} has sm_id value {$item->sm_id}"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With