将json字符串解码为数组

时间:2016-03-19 09:55:12

标签: php html

我无法将json字符串解码为数组,但是我收到以下错误。

  

错误:(我们处理您的请求时发生了解析错误。)

$value = '"latitude":"1.3704","longitude":"103.8471","city":"singapore"';

$jsondata = file_get_contents($value);
$db = json_decode($jsondata,true);  

for( $i = 0; $i < sizeof($db); $i++){
    $data = $db[$i];
    if( $data['city'] == $_POST['city'] ){
        if( isset($_POST['radius']) ){
            $distance = 6371000 * acos( cos( deg2rad($data['latitude']) ) * cos( deg2rad( $latitude ) ) * cos( deg2rad( $longitude ) - deg2rad($data['longitude']) ) + sin( deg2rad($data['latitude']) ) * sin( deg2rad( $latitude ) ) );
            if( $distance <= $radius ){
                $inradius = true;
            }
            else{
                $inradius = false;
            }
        }
        else{
            $inradius = true;
        }
        if( $data['price'] >= $minPrice && $data['price'] <= $maxPrice && $data['area'] >= $minArea && $data['area'] <= $maxArea && $inradius === true){
            if( empty( $_POST['slika'] ) ){
                $result[] = $data;
            }
            else{
                if( !empty( $data['images'] )){
                    $result[] = $data;
                }
            }
        }

1 个答案:

答案 0 :(得分:2)

这是无效的JSON:

"latitude":"1.3704","longitude":"103.8471","city":"singapore"

这是有效的JSON:

{"latitude":"1.3704","longitude":"103.8471","city":"singapore"}
^                                                             ^

最好的方法是使用内置函数json_encode()

$json = json_encode
(
    [ 'latitude' => '1.3704', 'longitude' => '103.8471', 'city' => 'singapore' ]
);