php 数组 获取键值,PHP数组_filter获取无键值

我来自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代替。提前谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值