简体   繁体   中英

fetching object from json string not working in php

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

this json obj in string format i am sending from android to php server. on php server string is printing correctly. but when i try to get "lng" "bookingId" from String is show null value . this is my php code.

// error on " ** line "

<?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));


?>

one more Questiong- see json string there - "lng": 78.9293102 ,"lat":22.0533 . there number 78.9293 and 22.0533 not in between " ". i saw other string there integer and double value also in between " ". does this create some problem ?

You need to use json_decode() to convert a JSON String to a native PHP data type.

Your data will be converted to a stdClass object and not an array by default, unless you use the second parameter of json_decode($string, TRUE); but there is no need to convert a perfectly good object into an array.

<?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;

i got solution .. my json is printing like this- {\\\\ "\\\\abc":\\[{"sdf":.......}] }

so i use $json = stripslashes($_REQUEST['tripRoute']);

this solved my problem. thank for your response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM