I have an array of objects.
A print_r
output looks like this:
Array
(
[0] => stdClass Object
(
[sm_id] => 1
[c_id] => 1
)
[1] => stdClass Object
(
[sm_id] => 1
[c_id] => 2
)
)
I am really struggling to find a way to loop though the results and access the object elements. If anyone could give me any pointers i would be extremely grateful.
Thanks in advance
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: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:Recursive traverse object or array with array or objects elements:
Use
OR
Assuming your
sm_id
andc_id
properties are public, you can access them by using aforeach
on the array: