4

我有一个这样的json字符串:

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

如何打印每个名称?稍后我将在 html 选择选项中使用它们,我知道该怎么做。但我无法把绳子拿出来。这是我尝试过的东西:

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

此时,我可以通过 打印客户数组echo json_encode($fields_detail),但在此之前,我想使用foreach. 我试了几次,都不行。任何人都可以帮忙吗?

谢谢!

4

4 回答 4

5

客户是一个对象数组,因此迭代每个对象并读取属性应该可以工作。

foreach ($fields_detail as $customer) {
  echo $customer->name;
}
于 2013-02-21T11:19:19.317 回答
3

像这样的东西:

$data = json_decode($fields_string, true); // return array not object
foreach($data['fields']['customers'] as $key => $customer) {
 echo $customer['name']; 
}
于 2013-02-21T11:21:04.800 回答
1

通过以下方式访问名称fields->customers

$obj = json_decode($fields_string);

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

演示

于 2013-02-21T11:29:25.297 回答
0
foreach($obj->fields->customers as $fields)
echo $fields->name;
于 2013-02-21T11:23:05.953 回答