2013-07-17 87 views
0

予有这种类型的JSON对象:在PHP解析JSON阵列和值添加到PHP阵列

{ 
    "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消息有问题?

+1

你能展示一些你所使用的代码? – Muc

+0

看起来“食物”和“质量”值本身是json字符串 –

+0

foreach($ parsedJSON-> order-> Food as $ mydata) { $ response [“test2”] = $ mydata; } – user1732457

回答

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 
) 
+0

thnx非常多,工作很好,虽然我认为我必须以不同的方式组织我的JSON,以便更容易处理 – user1732457

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