How to loop through array of objects in PHP

牧云@^-^@ 提交于 2019-12-13 07:49:19

问题


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) "alex@gmail.com"
    ["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) "michael@gmail.com"
    ["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;
    }

回答1:


$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.



来源:https://stackoverflow.com/questions/31753453/how-to-loop-through-array-of-objects-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!