在php中解析JSON数组并将值添加到php数组中

时间:2013-07-17 18:41:21

标签: php json

我有一个这种类型的json对象:

{
    "order": {
        "Food": "[Test 1, Test 2, Test 0, Test 3, Test 1, Test 3, Test 11, Test 7, Test 9, Test 8, Test 2]",
        "Quantity": "[2, 3, 6, 2, 1, 7, 10, 2, 0, 0, 1]"
    },
    "tag": "neworder"
}

我已经使用了json_decode,但我想把食物和数量中的值存储在一个php数组中,我尝试了很多方法,但实际上没有运气。 有人指出正确的方法,或者我的json消息有问题吗?

2 个答案:

答案 0 :(得分:2)

PHP json_decode的第二个参数设置为true将返回关联数组而不是对象。

另外,您的JSON有效,但使用json_decode时,您的Food条目会解析为字符串。为了拥有您想要的数组,此代码段将起作用:

<?php
$json  = '{"order":{"Food":"[Test 1, Test 2, Test 0, Test 3, Test 1, Test 3, Test 11, Test 7, Test 9, Test 8, Test 2]","Quantity":[2,3,6,2,1,7,10,2,0,0,1]},"tag":"neworder"}';
$array = json_decode($json, true);

// Fix Food array entry
$array['order']['Food'] = explode(', ', trim($array['order']['Food'], '[]'));

print_r($array);

这样你就可以得到一个PHP数组来随意操作:

Array
(
    [order] => Array
        (
            [Food] => Array
                (
                    [0] => Test 1
                    [1] => Test 2
                    [2] => Test 0
                    [3] => Test 3
                    [4] => Test 1
                    [5] => Test 3
                    [6] => Test 11
                    [7] => Test 7
                    [8] => Test 9
                    [9] => Test 8
                    [10] => Test 2
                )

            [Quantity] => Array
                (
                    [0] => 2
                    [1] => 3
                    [2] => 6
                    [3] => 2
                    [4] => 1
                    [5] => 7
                    [6] => 10
                    [7] => 2
                    [8] => 0
                    [9] => 0
                    [10] => 1
                )
        )
    [tag] => neworder
)

答案 1 :(得分:0)

如果:

{
    "order": {
        "Food": "[Test 1, Test 2, Test 0, Test 3, Test 1, Test 3, Test 11, Test 7, Test 9, Test 8, Test 2]",
        "Quantity": "[2, 3, 6, 2, 1, 7, 10, 2, 0, 0, 1]"
    },
    "tag": "neworder"
}

确实是你正在使用的json,那么你将不得不做一些工作来得到你想要的东西。

$obj = json_decode($json);
// the food and quantity properties are string not json.
$foods = explode("," trim($obj->order->Food;, "[]"));
$foods = array_map("trim", $foods); // get rid of the extra spaces
$quantitys = json_decode($obj->order->Quantity);

为了使它成为有效的json,它必须像

一样被创作
{
    "order": {
        "Food": ["Test 1", "Test 2", "Test 0", "Test 3", "Test 1", "Test 3", "Test 11", "Test 7", "Test 9", "Test 8", "Test 2"],
        "Quantity": [2, 3, 6, 2, 1, 7, 10, 2, 0, 0, 1]
    },
    "tag": "neworder"
}