2015-04-27 204 views
1

我怎麼會去訪問從Shopify JSON這些元素在PHP訪問某些JSON元素

JSON:

{ 
    "orders":[ 
     { "note_attributes":[ 
       { 
        "name":"account_id", 
        "value":"[email protected]" 
       }, 
       { 
        "name":"account_password", 
        "value":"xxxxxx" 
       }, 
       { 
        "name":"security_answer", 
        "value":"xxxxxx" 
       } 
      ], 

這只是片斷的對象。我如何訪問每個值並將其分配給名稱?例如,這個$ req ['account_id']將等於該名稱標籤的值。這是怎麼我試圖做到這一點,但它不工作:

foreach ($order['note_attributes'] as $attributes) { 


     $req = array(); 



     $req[$attributes->name] = $attributes[$attributes->value]; 


     } 

我會再像回聲$ REQ [「ACCOUNT_ID」]這將= [email protected]但它不工作有任何建議或修復?

+0

嘗試[json_decode](http://php.net/manual/en/function.json-decode.php),它會將json轉換爲php變量。 – Roopendra

回答

1

當遍歷對象屬性,一個方法是使用(如你有)foreach

// accessing property 
foreach ($objects as $object) { 
    echo $object->property; 
} 

// accessing key-value pair 
foreach ($object as $key => $value) { 
    echo "$key => $value\n"; 
} 

一個例子:

$attributes = array(); 
. 
. 
foreach($note_attributes as $note_attribute) { 
    $key = $note_attribute['name']; 
    $value = $note_attribute['value']; 
    $attributes[$key] = $value; 
} 

結構應在鍵 - 值對。即。

attributes [ 
    "account1234" => "[email protected]", 
    "account_password" => "asdasdasd" 
] 

希望這會有所幫助。

更新:正如Roopendra提到的,json_decode()帶有一個TRUE標誌,返回一個關聯數組,否則爲stdClass。