我来自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上:
$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
// )
// )
我没有用
array_search()
,因为我要搜索的针有2到3层深,比如:
array_filter($people, function ($person) use ($cityToFind) {
return $person['location']['city'] === $cityToFind;
}
我可以使用for循环,但我真的想用filter代替。提前谢谢!