如何遍历PHP中的对象数组

Ale*_*lka 1 php arrays stdclass

我对 PHP 很陌生,我需要你的帮助!我需要为我的应用程序编写后端,用于接收 json post 并将数据写入 json 文件。我坚持循环遍历数组。

$postData = file_get_contents("php://input");
$request = json_decode($postData);
var_damp($request)
Run Code Online (Sandbox Code Playgroud)

显示数组:

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"
 }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试遍历对象并出现错误

Object of class stdClass could not be converted to string

这是我尝试这样做的方法:

    foreach($request as $i => $i_value) {
        echo $i_value;
    }
Run Code Online (Sandbox Code Playgroud)

Gol*_*rol 6

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

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

foreach($request as $i => $i_value) {
    echo $i_value->name;
}
Run Code Online (Sandbox Code Playgroud)

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

如果对象实现了__toString()魔术方法,则只能像您一样将它们强制转换为字符串,但是由json_decode所创建的对象只是StdClass没有实现此功能的简单对象。您可能根本不打算这样做,但如果您感到好奇,您可以查看json_decode 到自定义类,以了解如何使用自定义类而不是 StdClass。