How to convert a JSON string into an array (PHP)?

前端 未结 4 1487
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 17:55

using the below code for decoding json

$categories = json_decode($data);
$categories = $categories->data;

where i get this



        
相关标签:
4条回答
  • 2021-01-14 18:15

    @Gordon seems correct - that looks like JSON. Assuming, though, that you're dealing with an "actual" PHP Object, then it will be iterable; simply run through it with a foreach and push each key/value pair into your destination array.

    0 讨论(0)
  • 2021-01-14 18:21

    This looks like a JSON string. You can use json_decode() to convert it into a PHP variable, e.g.

    $obj = json_decode($json);
    print_r($obj->categories); // array of StdClass objects
    

    You can access and iterate the categories array regularly

    echo $obj->categories[0]->name; // Utilities
    echo $obj->categories[1]->name; // Productivity
    echo $obj->categories[2]->name; // Music
    

    To convert the StdClass objects to arrays, you could do

    $categories = array();
    foreach (json_decode($json)->categories as $category) {
        $categories[] = (array) $category;
    }
    print_r($categories);
    

    You could also do it with a lambda function and array_map:

    // Before PHP5.3
    $categories = array_map(
        create_function('$el', 'return (array) $el;'), 
        json_decode($json)->categories);
    
    // After PHP5.3
    $categories = array_map(
        function($el) { return (array) $el; }, 
        json_decode($json)->categories);
    
    0 讨论(0)
  • 2021-01-14 18:25

    Erm, you can just set the 2nd parameter to convert JSON into an array instead of into an object:

    $categories = json_decode($data, true);
    
    0 讨论(0)
  • 2021-01-14 18:27

    take a look at get_object_vars http://php.net/manual/en/function.get-object-vars.php

    0 讨论(0)
提交回复
热议问题