如何将Json数据转换为适当的关联数组

时间:2016-11-15 08:00:38

标签: php arrays json

我有一些json数据,我从一个发布但无法处理它并且能够存储在数据库中,这里发布的数据是什么

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"}]
)

有什么方法可以将它改成关联数组,并且我能够对它们的名称进行分类。

我已经尝试了

$data = json_decode($your_json_string, TRUE);

1 个答案:

答案 0 :(得分:3)

我认为你可以这样吗

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

输出:

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
            )

    )