PHP Foreach Arrays and objects
Asked Answered
V

4

38

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?

Vino answered 4/12, 2012 at 16:50 Comment(0)
V
55

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;
}
Veliger answered 4/12, 2012 at 16:53 Comment(2)
Note that the $key=> part is not neededMidiron
But it's recommended to include the $key => part. According to this benchmark, the loop is twice as fast, when you include the $key part: phpbench.comLolly
D
7

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}";
}
Demimondaine answered 4/12, 2012 at 16:55 Comment(0)
A
4

Assuming your sm_id and c_id properties are public, you can access them by using a foreach on the array:

$array = array(/* objects in an array here */);
foreach ($array as $obj) {
    echo $obj->sm_id . '<br />' . $obj->c_id . '<br />';
}
Arcade answered 4/12, 2012 at 16:54 Comment(0)
G
2

Recursive traverse object or array with array or objects elements:

function traverse(&$objOrArray)
{
    foreach ($objOrArray as $key => &$value)
    {
        if (is_array($value) || is_object($value))
        {
            traverse($value);
        }
        else
        {
            // DO SOMETHING
        }
    }
}
Gumboil answered 6/4, 2014 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.