简体   繁体   中英

PHP iterate through array with dictionary

Hi Im new to php and I have an array that looks like the following code.

 [ { "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 .

   $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. You need to define it as a string and decode it. For print_r you also need brackets.

 $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. That way you can access the keys with the array['key'] syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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