简体   繁体   English

PHP使用字典遍历数组

[英]PHP iterate through array with dictionary

Hi Im new to php and I have an array that looks like the following code. 嗨,我是php新手,我有一个看起来像以下代码的数组。

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

How do I iterate and get all the amounts ? 如何迭代并获得所有金额? Tried using foreach and ended up with and invalid argument where I used . 尝试使用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'];
   } 

That's a JSON encoded array. 那是一个JSON编码的数组。 You need to define it as a string and decode it. 您需要将其定义为字符串并对其进行解码。 For print_r you also need brackets. 对于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']);
 } 

The true in json_decode makes sure that you only get arrays. json_decode中的true可以确保仅获取数组。 That way you can access the keys with the array['key'] syntax. 这样,您可以使用array['key']语法访问键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM