How to go through an array of objects accessing each element of the array with PHP

Asked

Viewed 1,390 times

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
            )

....

2 answers

1


PHP provides a way to define objects so that it is possible to iterate through a list of items, such as the statement 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 has passed through each of the visible variables that can be accessed.

Source: http://php.net/manual/en/language.oop5.iterations.php

0

You can use the foreach it works only on arrays and objetos, and will issue an error when trying to use it in a variable with a different data type or 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.