gpt4 book ai didi

PHP:嵌套的 json 和值提取

转载 作者:搜寻专家 更新时间:2023-10-31 21:09:51 25 4
gpt4 key购买 nike

我在下面有这个 json。我正在尝试使用 json_decode 获取值。我得到了一些值,但我在处理深层嵌套的值时遇到了麻烦。这是 json:

{
"startAt": 0,
"issue": [
{
"id": "51526",
"fields": {
"people": [
{
"name": "bob",
"emailAddress": "bob@gmail.com",
"displayName": "Bob Smith",
},
{
"name": "john",
"emailAddress": "john@gmail.com",
"displayName": "John Smith",
}
],
"skill": {
"name": "artist",
"id": "1"
}
}
},
{
"id": "2005",
"fields": {
"people": [
{
"name": "jake",
"emailAddress": "jake@gmail.com",
"displayName": "Jake Smith",
},
{
"name": "frank",
"emailAddress": "frank@gmail.com",
"displayName": "Frank Smith",
}
],
"skill": {
"name": "writer",
"id": "2"
}
}
}
]

}

我知道这样做可以获得一个值:

foreach ($decoded_array['issue'][0]['fields']['people'] as $person) {
echo $person['emailAddress'];
}

但是,有没有一种简单的方法可以获取 bob、john、jake 和 frank 的所有“emailAddresses”?

谢谢!

最佳答案

最简单的方法实际上就是循环,但首先在 $decoded_array['issue'] 嵌套循环,然后在 ['people'] 上嵌套循环。将您的地址收集到输出数组中。

// Note: this assumes you called json_decode() with the second
// param TRUE to force an associative array..
// $decoded_array = json_decode($input_json, TRUE);

$addresses = array();
foreach ($decoded_array['issue'] as $i) {
foreach ($i['fields']['people'] as $person) {
// Append the address onto an output array
$addresses[] = $person['emailAddress'];
}
}
// De-dupe them if necessary
$addresses = array_unique($addresses);
print_r($addresses);

// Prints
Array
(
[0] => bob@gmail.com
[1] => john@gmail.com
[2] => jake@gmail.com
[3] => frank@gmail.com
)

如果您不确定除了键名 emailAddress 之外的结构,一个稍微高级的方法是使用 array_walk_recurisve()遍历数组寻找那个键。这将收集名为 emailAddress所有键,而不仅仅是 ['people'] 子数组中的键。

$addresses = array();
// Pass $addresses into the closure by reference so you can write to it
array_walk_recursive($decoded_array, function($value, $key) use (&$addresses) {
// Find *all keys* called emailAddress
if ($key == 'emailAddress') {
$addresses[] = $value;
}
});

关于PHP:嵌套的 json 和值提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22851241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com