Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

Parse JSON Array in php and add values to php array

I have a json object of this type:

{
    "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"
}

I have used json_decode but i would like to take the values inside Food and Quantity and store them inside a php array, i ve tried many approaches but really with no luck. Could someone point to the right way to do it, or is something wrong with my json message??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

PHP json_decode's 2nd argument set to true will return associative arrays instead of objects.

Additionaly, your JSON is valid but your Food entry resolves to a string when using json_decode. In order to have the array you want this code snippet will work:

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

This way you'll get a PHP array to manipulate at will:

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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...