简体   繁体   English

PHP通过JSON数组循环

[英]php loop through json array

I have a json string like this: 我有一个像这样的json字符串:

$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. 稍后我将在html select选项中使用它们,我知道该怎么做。 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 . 此时,我可以通过echo json_encode($fields_detail)打印出客户数组,但是在此之前,我想使用foreach分解名称。 I tried several times, it didn't work. 我尝试了几次,但没有成功。 Can anyone help please. 谁能帮忙。

Thanks! 谢谢!

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;
}

Something like this: 像这样:

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

Access the names via fields->customers : 通过fields->customers访问名称:

$obj = json_decode($fields_string);

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

Demo 演示版

foreach($obj->fields->customers as $fields)
echo $fields->name;

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

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