猿问

PHP array_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:


<?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 循环,但我真的想使用过滤器。提前致谢!


函数式编程
浏览 153回答 2
2回答

繁星coding

你可以做几件事。要获取数组的第一个元素,您可以使用reset($found)&nbsp;https://www.php.net/manual/en/function.reset.php过滤数组后,您可以使用array_values($found)&nbsp;https://www.php.net/manual/en/function.array-values.php将数组键重置为从 0 开始

互换的青春

使用array_filter()将始终处理整个数组,在您的示例中,它是最后一个条目,因此无论如何都需要处理。但如果您有 500 个条目并且是第一个条目,它仍会检查所有 500 个条目。相反,您可以使用一个简单的foreach()循环,一旦找到第一个循环就停止......foreach ( $people as $index => $person )    {    if ( $person['username'] === $usernameToFind )  {        echo "Index={$index} name={$person['name']}";        break;    }}给...Index=2 name=Abraham
随时随地看视频慕课网APP
我要回答