Search code examples
phparraysjsonlaravel-7jsondecoder

Convert a json to multi-dimensional PHP array


I have the following json sent to my API endpoint

{"key":"levels","value":"[{role_id:1, access_level_id:3}, {role_id:2, access_level_id:1}, {role_id:3, access_level_id:2}]","description":""}

at the backend, I receive it as a Laravel request as follows:

public function functionName(Request $request){
    $req=$request->all();
    Log::debug($req['value']);
    return;
}

And it returns the following expected result

array ( 'key' => 'levels', 'value' => '[{role_id:1, access_level_id:3}, {role_id:2, access_level_id:1}, {role_id:3, access_level_id:2}]', 'description' => NULL, )

But I need to convert the 'value' to array also. so that I can have a multidimensional PHP array. So I expect to get something like

array ( 'key' => 'levels', 'value' => array( array('role_id'=>1, 'access_level_id'=>3), array('role_id'=>2, 'access_level_id'=>1), array('role_id'=>3, 'access_level_id'=>2) ) 'description' => NULL, )

but when in my Laravel method I do the following:

public function share_doc(Request $request){
        $req=$request->all();
        Log::debug(json_decode($req['value'],true));
        return;
    }

trying to convert the json received as 'value' to PHP array, it returns nothing -i.e. no value, no array, no string. Just nothing.

So, my struggle here is how I can convert the entire json string received as 'value' from the request to a PHP array so that I can iterate through the items with PHP

Thank you for helping


Solution

  • Your problem is that the value element is not valid JSON as the keys are not quoted. For the sample data you provide, you can fix that with preg_replace and then json_decode the changed value:

    $x['value'] = json_decode(preg_replace('/(\w+)(?=:)/', '"$1"', $x['value']), true);
    print_r($x);
    

    Output:

    Array
    (
        [key] => levels
        [value] => Array
            (
                [0] => Array
                    (
                        [role_id] => 1
                        [access_level_id] => 3
                    )
                [1] => Array
                    (
                        [role_id] => 2
                        [access_level_id] => 1
                    )
                [2] => Array
                    (
                        [role_id] => 3
                        [access_level_id] => 2
                    )
            )
        [description] => 
    )
    

    Demo on 3v4l.org