我如何从PHP中的Shopify JSON访问这些元素
JSON:
{
"orders":[
{ "note_attributes":[
{
"name":"account_id",
"value":"xxxxxxxxxxxx@gmail.com"
},
{
"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'],那将是= xxxxxxxxx@gmail.com但它没有任何建议或修正?
答案 0 :(得分: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" => "abc@xxx.com",
"account_password" => "asdasdasd"
]
希望这有帮助。
更新:正如Roopendra所说,json_decode()带有TRUE标志,返回一个关联数组,否则为stdClass。