如何从多维数组中返回第一个符合条件的子数组中的数据
我正在写一个函数,试图从API调用中获取一些配置。特定配置的ID来自一个名为 id 的查询字符串。一个用户可以有不同的配置,因此用这个ID来获取对应的配置。用于API调用的令牌存放在名为 token 的cookie中。
一切看起来都正常,但是在得到想要的输出方面我遇到了困难。我在使用 array_find 根据 id 找到正确的配置。我只想要与指定的 id 相关的数组中的 settings 部分。至于它为什么不返回数据,我不太确定,怀疑可能与API调用的时序有关,但希望有人能在这里指出问题所在。
这是我从API调用得到的数组的样子:
Array (
[conf] => Array (
[0] => Array (
[id] => 123
[configuration] => Array (
[title] => Settings 1
[settings] => Array (
[color] => blue
[size] => 800
)
)
)
)
以下是我的PHP代码:
$id = sanitize_text_field($_REQUEST['id']);
$data = json_decode($response, true);
print_r($data); // This one prints the whole array
$userConf = [];
array_find($data, function($conf) use ($id) {
if ($conf[0]['id'] === $id) {
$userConf = $conf[0]['configuration']['settings'];
$config = array(
'color' => sanitize_text_field($userConf['color'] ?? ''),
'size' => sanitize_text_field($userConf['size'] ?? '')
);
print_r($config); // This prints the correct part of the array
}
});
解决方案
看过你的问题,确实存在一些问题。你当然有一个拼写错误,但正如你在评论区澄清的,那并不是原始问题的一部分,而是在提问时添加的。首先,如果你查看 文档,你会看到这一段:
array_find() returns the value of the first element of an array for which the given callback returns true. If no matching element is found the function returns null.
所以基本上,你会从数组中得到一个值(如果没有这样的值则为 null),这是因为你传入的回调函数返回 true。你的回调需要返回一个值。我把回调内部的打印语句去除了,因为它们显然不属于那里,且只是用于调试。array_find 将返回数组中的一个值,因此你需要传入 $data['conf'] 才能得到一个合理的值。为了避免这种情况,你当然也想要结果的子数组,但这不是 array_find 的职责来提取那一部分。
因此我实现了一个解决方案,包含以下要点:
- 为你提供的
$data定义一个示例 - 略过响应中的
json_decode,因为这显然不是问题所在。 - 定义一个占位的
sanitize_text_field函数,以确保代码不会崩溃。 - 去掉回调内部不必要的实现,按应有的方式返回布尔值。
- 之后提取配置的设定;如果搜索没有结果,则回退到某个默认值。
<?php
$data = [
'conf' => [
0 => [
'id' => 123,
'configuration' => [
'title' => 'Settings 1',
'settings' => [
'color' => 'blue',
'size' => 800
]
]
]
]
];
function sanitize_text_field($input) {return $input;}
$userConf = [];
$id = 123;
$result = array_find($data['conf'], function($conf) use ($id) {
return ($conf['id'] === $id);
});
var_dump($result ? $result['configuration']['settings'] : 'not found');