2015-04-27 152 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。