2013-06-01 48 views
-1

我解析了從另一個網站發佈的JSON,其中一個節點有一個孩子。Php json_decode解析讀取子值

$inputJSON = file_get_contents('php://input'); 
$input= json_decode($inputJSON); //convert JSON into object 

$order_number = $input->{'order_no'}; 
$name = $input->{'name'}; 
$street_address = $input->{'address_1'}; 
$city =$input->{'city'}; 
$state = $input->{'region'} ; 
$zip = $input->{'postal_code'}; 

我可以讀取所有的值。然而,該產品部分的格式

<items> 
    <product_code></product_code> 
    <product_name></product_name> 
</items> 

我想它讀成

$product_id = $input->{'items'}{'product_code'}; 
$product_description = $input->{'items'}{'product_name'}; 

但我得到我的變量沒有數據。什麼是正確的語法?

謝謝。

編輯:JSON輸出

object(stdClass)#1 (20) { 
    ["test_order"]=> 
    string(1) "Y" 
    ["shop_no"]=> 
    string(6) "142319" 
    ["order_no"]=> 
    string(12) "TU5495467701" 
    string(5) "Smith" 
    ["city"]=> 
    string(5) "Bosei" 
    ["postal_code"]=> 
    string(6) "123456" 
    ["order_total"]=> 
    string(5) "39.00" 
    ["country"]=> 
    string(2) "HK" 
    ["telephone"]=> 
    string(8) "12345678" 
    ["pay_source"]=> 
    string(2) "CC" 
    ["base_currency"]=> 
    string(3) "USD" 
    ["items"]=> 
    array(1) { 
    [0]=> 
    object(stdClass)#2 (9) { 
     ["product_price"]=> 
     string(5) "39.00" 
     ["product_name"]=> 
     string(12) "Abcd Product" 
     ["product_code"]=> 
     string(8) "142319-1" 
    } 
    } 
    ["first_name"]=> 
    string(4) "John" 
} 
+0

這是XML,而不是JSON。真正的JSON可能看起來也可能不看起來像這樣。 – deceze

+0

添加了JSON輸出。 – Basu

回答

1

正如你寫道:

["items"]=> 
    array(1) { 
    [0]=> 
    object(stdClass)#2 (9) { 
     ["product_price"]=> 
     string(5) "39.00" 
     ["product_name"]=> 
     string(12) "Abcd Product" 
     ["product_code"]=> 
     string(8) "142319-1" 
    } 
    } 

items元素是一個數組,包含多個對象,所以你必須使用這個語法:

$product_id = $input->items[0]->product_code; 
$product_description = $input->items[0]->product_name; 

而且,如果items不止一個,你應該使用一個循環:

for ($i = 0; $i < count($input->items); $i++) { 
    $product_id = $input->items[$i]->product_code; 
    $product_description = $input->items[$i]->product_name; 
} 
+0

要麼全部是對象,要麼全是數組。你不會在對象中獲得這種嵌套數組。 – deceze

+0

@deceze是的,你完全**是正確的。我改變了我的答案。謝謝';)'。 – 2013-06-01 07:49:55

+0

試過這個:$ product_id = $ input-> items-> product_code; $ product_description = $ input-> items-> product_name;但仍然空白。 – Basu

0

我不是舒爾但我認爲你可以使用它作爲一個數組,做這樣的事情:

$product_id = $input['items']['product_code']; 
$product_description = $input['items']['product_name']; 
+2

默認情況下,'json_decode()'返回一個對象,而不是一個數組。 – Barmar

-2

在PHP json_decode返回數組。所以你應該可以在訪問數組值時簡單地訪問它。

$ product_id = $ input ['items'] ['product_code'];

+2

除非您將'$ assoc'參數設置爲'true',否則它會返回對象。 – Barmar

+0

巴馬爾說了些什麼。默認情況下,json_decode返回一個對象。 – Basu

1
$product_id = $input->items[0]->product_code; 

更可能的是,雖然您希望循環$input->items而不是直接訪問第一個索引。