我有以下字符串:
{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}],"Scan":"Whatever"}
我想在 php 中解码。该字符串是通过 sql 查询获得的。见下面的代码:
$TrackDetails_Query= "SELECT * FROM Tracks WHERE TrackID='".$TrackNum."' ORDER BY TrackID DESC";
$TrackDetails_Result= mysql_query($TrackDetails_Query) or die (mysql_error());
if (mysql_num_rows($TrackDetails_Result)==0){
echo 'There are no tracks for the number entered';
}
else{
$traces=$row['Traces'];
$decoded_traces=json_decode($traces);
echo $decoded_traces;
}
}
但是我得到了错误:
Catchable fatal error: Object of class stdClass could not be converted to string
最佳答案
您收到错误是因为您试图将 stdClass 对象转换为字符串,这是它不支持的。
而不是 echo $decoded_traces
尝试 var_dump($decoded_traces)
- 这将给出你解码的对象的诊断 View (我想这就是你想要的).你应该会发现它看起来像这样
class stdClass#1 (2) {
public $Coords =>
array(5) {
[0] =>
class stdClass#2 (4) {
public $Accuracy =>
string(2) "65"
public $Latitude =>
string(18) "53.277720488429026"
public $Longitude =>
string(18) "-9.012038778269686"
public $Timestamp =>
string(39) "Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"
}
[1] => (more of the same, edited for brevity)
[2] =>
[3] =>
[4] =>
}
public $Scan =>
string(8) "Whatever"
}
默认情况下,json_encode将像上面那样创建 stdClass 对象。如果您更喜欢关联数组,请将 true
作为第二个参数传递给 json_decode
,例如$decoded_traces=json_decode($traces, true);
此外,尽管不能将 stdClass 转换为字符串,但您自己的类可以 - 一个实现了 __toString 的类魔术方法可以转换为字符串!
关于php - 类 stdClass 的对象无法转换为字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17489771/