Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through array of objects in PHP

I'm very new to PHP and I need your help! I need to write backend for my app that receives json post and write data to json file. And I'm stuck with looping through array.

$postData = file_get_contents("php://input");
$request = json_decode($postData);
var_damp($request)

shows array:

array(2) {
  [0]=>
  object(stdClass)#1 (8) {
    ["name"]=>
    string(11) "Alex Jordan"
    ["email"]=>
    string(14) "[email protected]"
    ["phone"]=>
    int(123456789)
    ["street"]=>
    string(12) "street, str."
    ["city"]=>
    string(7) "Chicago"
    ["state"]=>
    string(7) "Chicago"
    ["zip"]=>
    string(5) "07202"
    ["$$hashKey"]=>
    string(8) "object:3"
  }
  [1]=>
  object(stdClass)#2 (8) {
    ["name"]=>
    string(15) "Michael Jonhson"
    ["email"]=>
    string(17) "[email protected]"
    ["phone"]=>
    float(11987654321)
    ["street"]=>
    string(12) "street, str."
    ["city"]=>
    string(11) "Los Angeles"
   ["state"]=>
   string(10) "California"
   ["zip"]=>
   string(5) "27222"
   ["$$hashKey"]=>
   string(8) "object:4"
 }
}

I'm trying to loop through the objects and getting error

Object of class stdClass could not be converted to string

Here is how I'm trying to do it:

    foreach($request as $i => $i_value) {
        echo $i_value;
    }
like image 578
Alexander Vovolka Avatar asked Jul 15 '26 10:07

Alexander Vovolka


1 Answers

$i_value is the object. Because it's an object you cannot just echo it (unlike in JavaScript where you can cast any object to string).

You can echo specific properties of the object:

foreach($request as $i => $i_value) {
    echo $i_value->name;
}

Of course you could also use var_dump again to dump each object. print_r should work too.

Objects can only be casted to string like you do if they implement the __toString() magic method, but the objects created by json_decode are just simple StdClass objects that do not implement this. It's probably not your intention to do this at all, but if you're curious, you may have a look at json_decode to custom class to see how you may use a custom class instead of StdClass.

like image 155
GolezTrol Avatar answered Jul 18 '26 00:07

GolezTrol