<?php
static $cnt=0;
$name='victor';
$coll = array(
'dep1'=>array(
'fy'=>array('john','johnny','victor'),
'sy'=>array('david','arthur'),
'ty'=>array('sam','joe','victor')
),
'dep2'=>array(
'fy'=>array('natalie','linda','molly'),
'sy'=>array('katie','helen','sam','ravi','vipul'),
'ty'=>array('sharon','julia','maddy')
)
);
function array_find($name,$arr)
{
global $cnt;
if(!(is_array($arr)))
return false;
foreach($arr as $val)
{
if(is_array($val))
array_find($name,$val);
else
{
$val=strtolower($val);
$item=strtolower($name);
if($val==$name)
$cnt+=1;
}
}
}
array_find($name,$coll);
if($cnt==0)
echo "$name was Not Found";
else
echo "$name was found $cnt times.";
1 Answer
Try this code, hope it will work
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
++$cnt;
}
}
array_walk_recursive($coll, 'recursive_search' , $name);
if ($cnt == 0)
echo "$name was Not Found";
else
echo "$name was found $cnt times.";
2 Comments
Always_Cool
yes, that is very helpful. Now how could i get the intermediate array name i.e. whether the name was found in "dep1" or "dep2" ?
Always_Cool
sry but i think u didn't got me right. i need to find the sub array name in which the name(s) was found. like victor was found in "dep1,dep2" sorry again if this que is pretty stupid to be asked :(
victor was found 2 times.isn't that right ?