Avatar ·

处理 PHP JSON 时出现错误 "Cannot use object of type stdClass as array"

大家好!我是 PHP 新手,遇到了一个奇怪的错误,无法理解。我写了一个脚本,从 API 获取 JSON 格式的数据,解码后尝试在循环中输出。这是我的代码: ```php $json = file_get_contents('https://api.example.com/users'); $data = json_decode($json); foreach ($data as $user) { echo $user['name'] . '
'; echo $user['email'] . '
'; } ``` 但运行时我得到:**Fatal error: Cannot use object of type stdClass as array**。我以为 json_decode() 返回数组,但显然不是。我哪里做错了?解码 JSON 后如何正确访问数据?我在网上找到了很多讨论,但没有针对我情况的具体解决方案。希望得到带示例的详细解释! P.S. 如果我执行 var_dump($data),会看到类似:`object(stdClass)#1 (2) { ["name"]=> string(4) "John" ["email"]=> string(15) "john@example.com" }`。所以这是一个对象,而不是数组。我该如何处理它?