How to traverse an array of objects by accessing each array element with PHP

0
[items:protected] => Array
    (
        [0] => stdClass Object
            (
                [id] => 130627
                [avatar] => 
                [first_name] => Prii
                [last_name] => Camargo
                [email] => [email protected]
                [name] => Sorocaba
                [ref_code] => pckystxa
                [banned] => 0
            )

        [1] => stdClass Object
            (
                [id] => 130583
                [avatar] => 
                [first_name] => Maicon
                [last_name] => França
                [email] => [email protected]
                [name] => Sorocaba
                [ref_code] => mfm73pn0
                [banned] => 0
            )

        [2] => stdClass Object
            (
                [id] => 130540
                [avatar] => 
                [first_name] => Rafael
                [last_name] => 0
                [email] => [email protected]
                [name] => Sorocaba
                [ref_code] => repakms
                [banned] => 0
            )

....

    
asked by anonymous 24.08.2018 / 21:48

2 answers

0

PHP provides a way to define objects so that it can be iterated through a list of items, such as the foreach . By default, all visible properties will be used for iteration.

Example # 1 Simple Object Iteration

<?php
class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:\n";
       foreach ($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach($class as $key => $value) {
    print "$key => $value\n";
}
echo "\n";


$class->iterateVisible();

?>

The above example will print:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

As the output shows, the foreach passed through each of the visible variables that can be accessed.

Source: link

    
25.08.2018 / 00:16
0

You can use foreach it works only on arrays and objetos , and will throw an error when trying to use it on a variable with a different data type or on an uninitialized variable.

foreach ($meu_array as $chave => $item_objeto){
    echo "Chave do Array: ".$chave."<br>";
    echo "id: ".$item_objeto->id;
    echo "first_name: ".$item_objeto->first_name;
    // Assim por diante ...
}

Documentation foreach

    
24.08.2018 / 21:59