Sagar Singh Sagar Singh - 18 days ago 8
JSON Question

How to convert Json data into proper associative array

I have some json data which i have posted from a from but can't process it and able to store in database, here is what data posted looks like

Array
(
[apd0] => [{"ratio":"1","size":"S","quantity":"83"},{"ratio":"2","size":"M","quantity":"166"}]
[apd1] => [{"ratio":"1","size":"S","quantity":"83"},{"ratio":"2","size":"M","quantity":"166"},{"ratio":"3","size":"N","quantity":"200"}]
)


is there any way i can change it into associative array and will i be able to classify their name.

I have already tried

$data = json_decode($your_json_string, TRUE);

Answer

i think you can it like this

$test = Array
    (
        'apd0' => '[{"ratio":"1","size":"S","quantity":"83"},{"ratio":"2","size":"M","quantity":"166"}]',
        'apd1' => '[{"ratio":"1","size":"S","quantity":"83"},{"ratio":"2","size":"M","quantity":"166"},{"ratio":"3","size":"N","quantity":"200"}]'
    );

    foreach($test as $key =>$val)
    {
        $array[$key] = json_decode($val, true);
    }

output:

Array
(
[apd0] => Array
    (
        [0] => Array
            (
                [ratio] => 1
                [size] => S
                [quantity] => 83
            )

        [1] => Array
            (
                [ratio] => 2
                [size] => M
                [quantity] => 166
            )

    )

[apd1] => Array
    (
        [0] => Array
            (
                [ratio] => 1
                [size] => S
                [quantity] => 83
            )

        [1] => Array
            (
                [ratio] => 2
                [size] => M
                [quantity] => 166
            )

        [2] => Array
            (
                [ratio] => 3
                [size] => N
                [quantity] => 200
            )

    )

)

Comments