0

我有一个这种类型的 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 但我想将 Food 和 Quantity 中的值存储在一个 php 数组中,我尝试了很多方法但真的没有运气。有人可以指出正确的方法,还是我的 json 消息有问题?

4

2 回答 2

2

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

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

<?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
)
于 2013-07-17T19:16:39.763 回答
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"
}
于 2013-07-17T18:59:56.747 回答