gpt4 book ai didi

php - 使用用户定义函数搜索 PHP 数组的优雅方式

转载 作者:IT王子 更新时间:2023-10-29 01:22:01 25 4
gpt4 key购买 nike

基本上,我希望能够获得 C++ 的 find_if()、Smalltalk 的 detect: 等的功能:

// would return the element or null
check_in_array($myArray, function($element) { return $elemnt->foo() > 10; });

但我不知道有任何 PHP 函数可以做到这一点。我想出了一个“近似值”:

$check = array_filter($myArray, function($element) { ... });
if ($check)
//...

这样做的缺点是代码的目的不是很清楚。此外,即使找到元素,它也不会停止对数组的迭代,尽管这更像是一个挑剔(如果数据集大到足以引起问题,线性搜索无论如何都不会成为答案)

最佳答案

从数组中拉出第一个,或者返回false:

current(array_filter($myArray, function($element) { ... }))

More info on current() here .

关于php - 使用用户定义函数搜索 PHP 数组的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14224812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com