【发布时间】:2021-07-16 16:42:00
【问题描述】:
不知道为什么会出现以下错误:
Uncaught Error: Object of class stdClass could not be converted to string
我正在学习这里的教程:
https://www.youtube.com/watch?v=ZIsdbVOQJNc&t=20s
大约 6:16 分钟是我所在的位置。
这是我的代码:
<?php
$url = "http://localhost/restapi/";
$data_array = array(
'username' => 'jbeasley',
'fullname' => 'John Beasley',
'email' => 'jbeasley@email.com'
);
$data = http_build_query($data_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
if($e = curl_error($ch)) {
echo $e;
} else {
$decoded = json_decode($resp);
foreach($decoded as $key => $val) {
echo $key . ': ' . $val . '<br>'; // <-- error is pointing here
}
}
curl_close($ch);
?>
错误指向foreach循环中的$val变量。
实际的 API 如下所示:
<?php
require_once __DIR__ . '/config.php';
class API {
function Select() {
$db = new Connect;
$users = array();
$data = $db->prepare('SELECT * FROM users');
$data->execute();
while($OutputData = $data->fetch(PDO::FETCH_ASSOC)) {
// $users[$OutputData['username']] = array(
$users[] = array(
'username' => $OutputData['username'],
'fullname' => $OutputData['fullname'],
'email' => $OutputData['email']
);
}
return json_encode($users);
}
}
$API = new API;
header('Content-Type: application/json');
echo $API->Select();
?>
我做错了什么,我该如何解决?
【问题讨论】:
-
你有一个数组,你的循环试图回显一个数组。在其中添加另一个循环,这样您就可以遍历子数组的键/值
-
@aynber - 我不明白。我跟着教程。
-
$decoded是一个用户数组。如果您在该循环内var_dump($val);,您会看到$val是包含单个用户的数组。您需要添加另一个循环才能进入用户数组。