How to loop through this json decoded data in PHP?

后端 未结 5 999
一向
一向 2020-12-10 21:40

I\'ve have this list of products in JSON that needs to be decoded:

\"[{\"productId\":\"epIJp9\",\"name\":\"Product A\",\"amount\":\"5\",\"identifier\":\"242\         


        
相关标签:
5条回答
  • 2020-12-10 22:03

    Try like following codes:

    $json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
    
    $array = json_decode($json_string);
    
    foreach ($array as $value)
    {
       echo $value->productId; // epIJp9
       echo $value->name; // Product A
    }
    

    Get Count

    echo count($array); // 2
    
    0 讨论(0)
  • 2020-12-10 22:09

    You can try the code at php fiddle online, works for me

     $list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
    
    $decoded_list = json_decode($list); 
    
    echo count($decoded_list);
    print_r($decoded_list);
    
    0 讨论(0)
  • 2020-12-10 22:11

    To convert json to an array use

     json_decode($json, true);
    
    0 讨论(0)
  • 2020-12-10 22:20

    Did you check the manual ?

    http://www.php.net/manual/en/function.json-decode.php

    Or just find some duplicates ?

    How to convert JSON string to array

    Use GOOGLE.

    json_decode($json, true);
    

    Second parameter. If it is true, it will return array.

    0 讨论(0)
  • 2020-12-10 22:23

    You can use json_decode() It will convert your json into array.

    e.g,

    $json_array = json_decode($your_json_data); // convert to object array
    $json_array = json_decode($your_json_data, true); // convert to array
    

    Then you can loop array variable like,

    foreach($json_array as $json){
       echo $json['key']; // you can access your key value like this if result is array
       echo $json->key; // you can access your key value like this if result is object
    }
    
    0 讨论(0)
提交回复
热议问题