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

前端 未结 4 1486
佛祖请我去吃肉
佛祖请我去吃肉 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: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);
    

提交回复
热议问题