問題描述
基本上,我希望能夠獲得 C++ 的 find_if()
、Smalltalk 的 detect:
等的功能:
Basically, I want to be able to get the functionality of C++'s find_if()
, Smalltalk's detect:
etc.:
// would return the element or null
check_in_array($myArray, function($element) { return $elemnt->foo() > 10; });
但我不知道有任何 PHP 函數可以做到這一點.我想出的一個近似值":
But I don't know of any PHP function which does this. One "approximation" I came up with:
$check = array_filter($myArray, function($element) { ... });
if ($check)
//...
這樣做的缺點是代碼的目的不是很明確.此外,即使找到了元素,它也不會停止遍歷數組,盡管這更像是一個挑剔(如果數據集大到足以引起問題,則無論如何線性搜索都不是答案)
The downside of this is that the code's purpose is not immediately clear. Also, it won't stop iterating over the array even if the element was found, although this is more of a nitpick (if the data set is large enough to cause problems, linear search won't be an answer anyway)
推薦答案
您可以編寫自己的函數 ;)
You can write your own function ;)
function callback_search ($array, $callback) { // name may vary
return array_filter($array, $callback);
}
這可能看起來沒用,但它增加了語義并可以增加可讀性
This maybe seems useless, but it increases semantics and can increase readability
這篇關于使用用戶定義函數搜索 PHP 數組的優雅方式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!