Aniket Singh
Aniket Singh

Reputation: 877

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);

Upvotes: 1

Views: 103

Answers (1)

Frankich
Frankich

Reputation: 852

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
            )

    )

)

Upvotes: 3

Related Questions