-1

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'];
   } 
  • Possible duplicate of [php: loop through json array](https://stackoverflow.com/questions/4731242/php-loop-through-json-array) – e_i_pi Jan 21 '18 at 22:59
  • Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – mickmackusa Jan 21 '18 at 23:01

1 Answers1

2

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.

jh1711
  • 2,288
  • 1
  • 12
  • 20
  • "JSON encoded array" This isn't an encoded array. It's a simple JSON string, not an array. it is encoded if you actually use *json_encode()* to convert it back though. – Thielicious Jan 21 '18 at 23:06