PHP使用字典迭代数组

时间:2018-01-21 22:46:27

标签: php arrays sorting dictionary

嗨,我是php新手,我有一个类似下面代码的数组。

 [ { "amount" : "204", "order" : "15", "customer": "12"}, { "amount" : "208", "order" : "17", "customer": "18"},{ "amount" : "300", "order" : "15", "customer": "19"} ]

如何迭代并获得所有金额?尝试使用foreach并最终使用我使用的无效参数。

   $xabo = [ { "amount" : "204", "order" : "15", "customer": "12"}, { "amount" : "208", "order" : "17", "customer": "18"},{ "amount" : "300", "order" : "15", "customer": "19"} ] 
   foreach($xabo as $denge){
   print_r $denge['amount'];
   } 

1 个答案:

答案 0 :(得分:2)

这是一个JSON编码的数组。您需要将其定义为字符串并对其进行解码。对于print_r,您还需要括号。

 $xabo_str = '[ { "amount" : "204", "order" : "15", "customer": "12"}, { "amount" : "208", "order" : "17", "customer": "18"},{ "amount" : "300", "order" : "15", "customer": "19"} ]';
 $xabo = json_decode($xabo_str, true);
 foreach($xabo as $denge){
   print_r($denge['amount']);
 } 

json_decode中的true确保您只获得数组。这样您就可以使用array['key']语法访问密钥。