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の 2 番目の引数を 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
)
于 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 に答える