我有 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 循環,但我真的想使用過濾器。提前致謝!
2 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
你可以做幾件事。
要獲取數組的第一個元素,您可以使用
reset($found)
https://www.php.net/manual/en/function.reset.php過濾數組后,您可以使用
array_values($found)
https://www.php.net/manual/en/function.array-values.php將數組鍵重置為從 0 開始

互換的青春
TA貢獻1797條經驗 獲得超6個贊
使用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
- 2 回答
- 0 關注
- 191 瀏覽
添加回答
舉報
0/150
提交
取消