我有以下字符串:
{"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
答案 0 :(得分:21)
您收到错误是因为您试图将stdClass对象转换为字符串,这是它不支持的。
而不是echo $decoded_traces
尝试var_dump($decoded_traces)
- 这将提供您已解码的对象的诊断视图(我认为这是您想要的)。你会发现它看起来像这样
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魔法的类可以转换为字符串!
答案 1 :(得分:3)
使用json_encode($traces)
这会将数组转换为字符串。 json_decode()
用于将字符串转换为数组或对象数组
答案 2 :(得分:3)
尝试使用此功能
$decoded_traces=json_decode($traces, true);
而不是这个
$decoded_traces=json_decode($traces);
它会将你的stdClass转换为数组。请注意,$decoded_traces
是数组,然后您可以根据需要使用。
答案 3 :(得分:2)
这是一个古老的问题,仍然可以回答那些像我一样遇到它的人。
尝试json_encode($ traces);
在我的情况下
return var_dump(json_encode($result[0]));
结果是:
string(34) "{"id":1,"content":"test database"}"
答案 4 :(得分:0)
$decoded_traces
是一个对象。你不能简单地echo
一个对象,因为这没有意义。
如果要调试对象,请使用var_dump($decoded_traces)
。
答案 5 :(得分:0)
代替
$decoded_traces=json_decode($traces);
echo $decoded_traces;
尝试
$decoded_traces=json_decode($traces, true);
print_r $decoded_traces;