Parsing JSON in PHP “stdClass could not be converted to string” error

六眼飞鱼酱① 提交于 2019-12-20 06:26:54

问题


I had this string:

{\"lat\":37.790388261934424,\"lng\":-122.46047996826172},{\"lat\":37.789608231530124,\"lng\":-122.46344112701416}

Then thanks to the help of StackOverflowers, I did this to strip the slashes:

$markers = stripslashes($markers);

Then I tried to add the outside brackets which seemed to be needed by the decode function

$markers = json_decode('['.$markers.']');

Was that the right way to go about it? Then I tried to do this:

foreach($markers as $key => $value) 
{
    $some_string = $some_string.' ( '.$value.' ) ';
}

Which game me this error:

Object of class stdClass could not be converted to string

But what I really need is to extract the lat/lng values into $lat , $lng variables. Could someone suggest to me how to fix the error I am getting and put the values into the variables?

Thanks, Alex


回答1:


Try...

foreach($markers as $marker) 
{
     $some_string .= '('.$marker->lat.','.$marker->lng.')';
}

Result...

(37.7903882619,-122.460479968)(37.7896082315,-122.463441127)



回答2:


foreach($markers as $key => $value) 
{
    // $value is object with lat and lng properties 
    $some_string = $some_string.' ( lat:'.$value->lat.' ) ';
}



回答3:


This was something that puzzled me too, why is json_decode() returning the data encapsulated in objects?

It turns out that all arrays in Javascript are considered objects, hence json_decode() returns them as objects of the PHP stdClass. Try to do print_r() on the $marker to see how it is structured.




回答4:


This here works

var json = JSON.parse(<?php echo "'" . stripslashes($_POST['json']) . "'" ?>);


来源:https://stackoverflow.com/questions/5527436/parsing-json-in-php-stdclass-could-not-be-converted-to-string-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!