PHP loop through json array

I have a json line:

$fields_string = ' {"fields": {"customers":[{"name":"john","id":"d1"}, {"name":"mike","id":"d2"}, {"name":"andrew","id":"d3"}, {"name":"peter","id":"d4"}] } }' 

How can I print each name? I will use them later in html choices, I know how to do this. But I could not pull the string. Here is what I tried:

 $obj = json_decode($fields_string); $fields_detail = $obj-?{"fields"}->{"customers"}; 

at this point I can print the array of clients using echo json_encode($fields_detail) , but before that I want the name to be broken using foreach . I tried several times, this did not work. Can someone help please.

Thanks!

+4
source share
4 answers

Clients are an array of objects, so iterating over each object and reading the property should work.

 foreach ($fields_detail as $customer) { echo $customer->name; } 
+5
source

Something like that:

 $data = json_decode($fields_string, true); // return array not object foreach($data['fields']['customers'] as $key => $customer) { echo $customer['name']; } 
+3
source

Access to names through fields->customers :

 $obj = json_decode($fields_string); foreach($obj->fields->customers as $customer) { echo $customer->name . "\n"; } 

Demo

+1
source
 foreach($obj->fields->customers as $fields) echo $fields->name; 
0
source

All Articles