【问题标题】:How to loop through array of objects in PHP如何在PHP中遍历对象数组
【发布时间】:2015-10-23 13:30:18
【问题描述】:

我是 PHP 新手,需要您的帮助! 我需要为接收 json post 并将数据写入 json 文件的应用程序编写后端。我被困在循环数组中。

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

显示数组:

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"
 }
}

我正在尝试遍历对象并得到错误

Object of class stdClass could not be converted to string

这是我的尝试:

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

【问题讨论】:

  • echo $i_value->name; etc... 或者 foreach 对象也是如此。

标签: php arrays stdclass


【解决方案1】:

$i_value 是对象。因为它是一个对象,所以你不能只是回显它(不像在 JavaScript 中你可以将任何对象转换为字符串)。

您可以回显对象的特定属性:

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

当然,您也可以再次使用var_dump 转储每个对象。 print_r 也应该可以工作。

如果对象实现了__toString() magic method,则它们只能像您一样转换为字符串,但json_decode 创建的对象只是简单的StdClass 对象,没有实现这一点。您可能根本不打算这样做,但如果您好奇,可以查看json_decode to custom class,了解如何使用自定义类而不是 StdClass。

【讨论】:

    【解决方案2】:

    我最近遇到了同样的问题。我使用for 循环遍历数组,这给了我undefined offset 的错误。使用isset() 解决了undefined offset 的错误。我知道现在回答这个问题为时已晚,但这是为将来可能正在寻找它的人准备的

    $postData = file_get_contents("php://input");
    $request = json_decode($postData);
    // or you can do $postData = json_decode(file_get_contents("php://input"));
    $arrayOfUsers = $request->data; // I used a key of data while sending the array via fetch API
    
    for($x = 0; $x < count($arrayOfUsers); $x++)
    {
        if(isset($arrayOfUsers[$x]))
        {
            $name = $arrayOfUsers[$x]->name;
            $email = $arrayOfUsers[$x]->email;
            $phone = $arrayOfUsers[$x]->phone;
            $street = $arrayOfUSers[$x]->street;
            // .... and so on
           // then you can do whatever you want with the data
        } else {
          echo "No Data Found";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      相关资源
      最近更新 更多