从 JSON 字符串中获取对象在 PHP 中不起作用


fetching object from json string not working in php

{
    "tripRoute": [{
        "lng": 78.92939102,
        "lat": 22.0533782
    }, {
        "lng": 78.92939102,
        "lat": 22.0533782
    }],
    "bookingId": 195
}

这个字符串格式的 JSON obj 我从 Android 发送到 PHP 服务器。 在 PHP 服务器上字符串打印正确。 但是当我尝试从字符串中获取"LNG"bookingId"时显示空值。 这是我的PHP代码。

"** 行"上的错误

<?php
    include('db_connection.php'); 
    $json= $_REQUEST['tripRoute'];
    $array = json_decode($json,true);
**  $data = $array['tripRoute'][0]['lng'];  // showing Null 

**  $flag['TripPathcode']= $array['bookingId'];   // showing null
    print(json_encode($flag));

?>

还有一个问题 - 见那里的 json 字符串 - "lng":78.9293102 ,"纬度":22.0533 .数字 78.9293 和 22.0533 不在 " " 之间。我看到其他字符串也在" "之间有整数和双精度值。 这会产生一些问题吗?

您需要

使用 json_decode() 将 JSON 字符串转换为本机 PHP 数据类型。

默认情况下,您的数据将被转换为 stdClass 对象而不是数组,除非您使用 json_decode($string, TRUE); 的第二个参数,但不需要将一个完美的对象转换为数组。

<?php
$js = '{
    "tripRoute": [{
        "lng": 78.92939102,
        "lat": 22.0533782
    }, {
        "lng": 78.92939102,
        "lat": 22.0533782
    }],
    "bookingId": 195
}';
$obj = json_decode($js);
print_r($obj);

echo $obj->tripRoute[0]->lng;
echo $obj->bookingId;

我得到了解决方案..我的 JSON 是这样打印的——{'''' "''''abc":''[{"sdf":.......}]}

所以我用$json = 条形斜杠($_REQUEST['tripRoute']);

这解决了我的问题。感谢您的回复。