Sel*_*lva 5 php recursion multidimensional-array
我想要一个简单的方法来计算字符串"Apple"在给定中出现的次数
# My Array :
$arr = array(
1 => "Apple",
2 => "Orange",
3 => array(1=>"Bananna",2=>"Apple"),
4 => "Grape",
5 => "Apple",
6 => array(1=>"Grape"),
7 => "Orange");
# Want to count only "Apple"
$needle = "Apple";
# My Function :
function arrsearch($needle,$haystack,$return) {
if(!is_array($haystack)) {
return false;
}
foreach($haystack as $key=>$val) {
if(is_array($val)) {
$return = arrsearch($needle,$val,$return);
}else if(strtolower($val) == strtolower($needle)) {
$return[] = $key;
}
}
return $return;
}
$var = arrsearch("Apple",$arr,array());
echo " Output : ".count($var);
# Output : 3
Run Code Online (Sandbox Code Playgroud)
我使用上面的函数来查找数组中字符串"Apple"的次数.建议我最好的一个.
你可以使用array_walk_recursive:
function search_for($arr, $term)
{
$count = 0;
array_walk_recursive($arr, function($item, $idx, $term) use (&$count) {
if (false !== stripos($item, $term)) {
++$count;
}
}, $term);
return $count;
}
search_for($arr, 'Apple'); // returns 3
Run Code Online (Sandbox Code Playgroud)
表达式function($item, $idx, $term) use (&$count) { .. }是一个匿名函数声明; 它就像常规函数一样工作,但是你可以通过使用use ($var)或者use (&$var)如果你需要修改它来从父作用域继承变量.可以在手册页上找到更多示例.
更新
对于PHP <5.3的版本,您必须使用对象封装计数器:
class RecursiveArraySearcher
{
private $c = 0;
public static function find($arr, $term)
{
$obj = new self;
array_walk_recursive($arr, array($obj, 'ismatch'), $term);
return $obj->c;
}
public function ismatch($item, $key, $term)
{
if (false !== stripos($item, $term)) {
++$this->c;
}
}
}
echo RecursiveArraySearcher::find($arr, 'Apple'); // 3
Run Code Online (Sandbox Code Playgroud)