php loop through json array

2020-04-08 05:33发布

I have a json string like this:

$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 a html select options, I know how to do that. But I couldn't get the string out. Here are something I tried:

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

at this point, I am able to print the customer array out by echo json_encode($fields_detail), but before that, I want to get the name break down using foreach. I tried several times, it didn't work. Can anyone help please.

Thanks!

4条回答
倾城 Initia
2楼-- · 2020-04-08 06:00

Customers is an array of objects so iterating over each object and reading the property should work.

foreach ($fields_detail as $customer) {
  echo $customer->name;
}
查看更多
Luminary・发光体
3楼-- · 2020-04-08 06:10

Something like this:

$data = json_decode($fields_string, true); // return array not object
foreach($data['fields']['customers'] as $key => $customer) {
 echo $customer['name']; 
}
查看更多
你好瞎i
4楼-- · 2020-04-08 06:10

Access the names via fields->customers:

$obj = json_decode($fields_string);

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

Demo

查看更多
家丑人穷心不美
5楼-- · 2020-04-08 06:12
foreach($obj->fields->customers as $fields)
echo $fields->name;
查看更多
登录 后发表回答