2013-07-17 86 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" 
}