How to access JSON decoded array in PHP

后端 未结 6 1099
梦谈多话
梦谈多话 2020-12-01 14:23

I returned an array of JSON data type from javascript to PHP, I used json_decode($data, true) to convert it to an associa

相关标签:
6条回答
  • 2020-12-01 14:36

    As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:

    $myArray = json_decode($data, true);
    echo $myArray[0]['id']; // Fetches the first ID
    echo $myArray[0]['c_name']; // Fetches the first c_name
    // ...
    echo $myArray[2]['id']; // Fetches the third ID
    // etc..
    

    If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:

    echo $myArray[0]->id;
    
    0 讨论(0)
  • 2020-12-01 14:39

    As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:

    <?php
    $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    
    var_dump(json_decode($json));
    var_dump(json_decode($json, true));
    
    ?>
    
    0 讨论(0)
  • 2020-12-01 14:39

    When you want to loop into a multiple dimensions array, you can use foreach like this:

    foreach($data as $users){
       foreach($users as $user){
          echo $user['id'].' '.$user['c_name'].' '.$user['seat_no'].'<br/>';
       }
    }
    
    0 讨论(0)
  • 2020-12-01 14:40
    $data = json_decode(...);
    $firstId = $data[0]["id"];
    $secondSeatNo = $data[1]["seat_no"];
    

    Just like this :)

    0 讨论(0)
  • 2020-12-01 14:46

    This may help you!

    $latlng='{"lat":29.5345741,"lng":75.0342196}';
    $latlng=json_decode($latlng,TRUE); // array
    echo "Lat=".$latlng['lat'];
    echo '<br/>';
    echo "Lng=".$latlng['lng'];
    echo '<br/>';
    
    
    
    $latlng2='{"lat":29.5345741,"lng":75.0342196}';
    $latlng2=json_decode($latlng2); // object
    echo "Lat=".$latlng2->lat;
    echo '<br/>';
    echo "Lng=".$latlng2->lng;
    echo '<br/>';
    
    0 讨论(0)
  • 2020-12-01 14:56
    $data = json_decode($json, true);
    echo $data[0]["c_name"]; // "John"
    
    
    $data = json_decode($json);
    echo $data[0]->c_name;      // "John"
    
    0 讨论(0)
提交回复
热议问题