通过JSON数组PHP循环 [英] php loop through json array

查看:173
本文介绍了通过JSON数组PHP循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON字符串是这样的:

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"}]
   }
}'

我如何打印每一个名字?我会用他们后来在HTML选择选项,我知道该怎么做。但我不能得到字符串出来。
下面是一些我尝试:

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

在这一点上,我能够打印客户阵列出由回声json_en code($ fields_detail),但在此之前,我想要得到的名称中使用分解的foreach 。我试了好几次,但没有奏效。任何人都可以请帮助。

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.

谢谢!

推荐答案

客户为对象,所以遍历每个对象和读取属性应该工作的数组。

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

这篇关于通过JSON数组PHP循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆