我有 Javascript 背景,我正在尝试使用array_filter(),但它的工作方式与 JS 有很大不同。
以这个 JS 为例:
const people = [
{
name: 'Will',
username: 'will',
},
{
name: 'Alex',
username: 'alex',
},
{
name: 'Abraham',
username: 'abraham',
},
];
const usernameToFind = 'abraham';
const found = people.filter(person => person.username === usernameToFind);
console.log(found[0]); // index 0
// {
// name: 'Abraham',
// username: 'abraham'
// }
我希望所有用户名都不同,因此它总是只返回一个值。因此,如果我想访问找到的信息,我只需要索引即可0。
关于 PHP:
<?php
$people = [
[
'name' => 'Alex',
'username' => 'alex',
],
[
'name' => 'Will',
'username' => 'will',
],
[
'name' => 'Abraham',
'username' => 'abraham',
],
];
$usernameToFind = 'abraham';
$found = array_filter($people, function($person) use ($usernameToFind) {
return $person['username'] === $usernameToFind;
});
print_r($found);
// Array
// (
// [2] => Array
// (
// [name] => Abraham
// [username] => abraham
// )
// )
所以我的问题是:我得到一个包含找到的元素索引的数组,但我不知道索引是什么。
我看到了这个问题,但它是完全不同的:PHP array_filter to get only one value from an array。
我没有使用array_search(),因为我的搜索针有 2 或 3 层深度,例如:
array_filter($people, function ($person) use ($cityToFind) {
return $person['location']['city'] === $cityToFind;
}
我可以使用 for 循环,但我真的想使用过滤器。提前致谢!
繁星coding
互换的青春