php - 从 JSON 数组获取电子邮件
问题描述
我正在尝试使用 fiken.no 的 API 来检索客户编号。API 是基于 HAL+JSON 的,我想用 PHP 访问数据。
创建新帐户时,您不会收到任何响应,而只会收到 HTTP 201,因此要获取生成的客户编号,我需要使用搜索端点。
该端点仅返回所有用户,如下所示:
{
"_links": {
"self": {
"href": "https://fiken.no/api/v1/companies/fiken-demo-personlig-gnist-enk/contacts"
}
},
"_embedded": {
"https://fiken.no/api/v1/rel/contacts": [
{
"_links": {
"self": {
"href": "https://fiken.no/api/v1/companies/fiken-demo-personlig-gnist-enk/contacts/757941482"
}
},
"name": "Ola Nordmann 2",
"email": "mail@mail.com",
"address": {
"country": "Norge"
},
"customerNumber": 10003
},
{
"_links": {
"self": {
"href": "https://fiken.no/api/v1/companies/fiken-demo-personlig-gnist-enk/contacts/757941171"
}
},
"name": "Ola Nordmann 1",
"email": "findthis@example.com",
"address": {
"country": "Norge"
},
"customerNumber": 10002
},
{
"_links": {
"self": {
"href": "https://fiken.no/api/v1/companies/fiken-demo-personlig-gnist-enk/contacts/756867201"
}
},
"name": "Demoleverandør",
"address": {
"address1": "Demoveien 44",
"address2": "",
"postalPlace": "Oslo",
"postalCode": "0190",
"country": "Norge"
},
"supplierNumber": 20001
},
{
"_links": {
"self": {
"href": "https://fiken.no/api/v1/companies/fiken-demo-personlig-gnist-enk/contacts/756867200"
}
},
"name": "Demokunde",
"address": {
"address1": "Demoveien 22",
"address2": "",
"postalPlace": "Oslo",
"postalCode": "0190",
"country": "Norge"
},
"customerNumber": 10001
}
]
}}
从这个响应中,我需要查询 f.ex 电子邮件 findthis@example.com 并从中获取整个用户对象。这包括地址数据,尤其是客户编号。我该怎么做?
我发现了这一点:Search a key in a Json (nested array) PHP这看起来像我的问题,但这里的键在 JSON 数组中是常量。这里是从 0 到无穷大。
有没有比普通 JSON 实践更好的方法来使用 PHP 来处理这个问题?
解决方案
首先是将 JSON 解码为数组:
$resultArray = json_decode($yourJSONvariable, true);
接下来我建议从 JSON 数组中分离联系人数组:
$contacts = $resultArray["_embedded"]["https://fiken.no/api/v1/rel/contacts"];
现在$contacts
应该是来自 API 调用的所有联系人的数组。您可以遍历每一个以查找具有匹配电子邮件的记录,如下所示:
foreach ($contacts as $contact) {
if ($contact["email"] == "findthis@example.com") {
$mycontact = $contact;
break;
}
}
$mycontact
现在将包含具有匹配电子邮件的联系人数组,您可以使用字段名称作为数组索引(例如,、、、)访问其$mycontact["name"]
各个$mycontact["address"]["country"]
字段$mycontact["_links"]["self"]["href"]
。要查看数组中的所有数据,请执行var_dump($contacts)
推荐阅读
- html - 将 HTML 包含到另一个 HTML 中
- android - 在firebase中获取嵌套数据
- android - 从活动中获取嵌套在导航控制器内的片段实例
- javascript - 光滑的轮播不工作,我做错了什么?
- asp.net-core - 拒绝不具有预期结构的 HTTP 请求
- uiscrollview - SwiftUI ScrollView 奇怪的垂直拉伸
- java - 如何检查数组是否已满,如果未满则添加?
- python - 如何在同一个脚本 PYTHON 上绘制多个图形
- vector - SystemVerilog 如何执行 one-hot masking
- influxdb - 在 InfluxDB 中使用不同操作对事件计数进行建模