无法将类stdClass的对象转换为字符串错误 [英] Object of class stdClass could not be converted to string error
问题描述
我有以下字符串:
{"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查询获得的.参见下面的代码:
Which I want to decode in php. The string is obtained via a sql query. See code below:
$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对象转换为字符串,这是它不支持的.
You get the error because you are trying to turn a stdClass object into a string, something it doesn't support.
而不是echo $decoded_traces
,请尝试var_dump($decoded_traces)
-这将为您解码后的对象提供诊断视图(我想这就是您想要的).您应该会发现它是这样的
Instead of echo $decoded_traces
try var_dump($decoded_traces)
- that will give a diagnostic view of the object you've decoded (which I presume is what you wanted). You should find it looks like this
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);
By default, json_encode will create stdClass objects like the above. If you would prefer an associative array, pass true
as the second parameter to json_decode
, e.g. $decoded_traces=json_decode($traces, true);
此外,尽管不能将stdClass转换为字符串,但是您自己的类可以-实现
As a further aside, although stdClass can't be turned into a string, your own classes can - a class which implements the __toString magic method could be converted to a string!
这篇关于无法将类stdClass的对象转换为字符串错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!