php - how to find a element in a nested array and get its sub array index -


when searching element in nested array, it's 1st level nesting index.

<?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){        /* want sub array index returned */     } } 

?>

i.e say, if i'am searching 'victor', have 'dep1' return value. ??

try:

$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')     ) );  $iter = new recursiveiteratoriterator(new recursivearrayiterator($coll), recursiveiteratoriterator::self_first);  /* these used keep record of    current parent element it's accessing childs of */ $parent_index = 0; $parent = ''; $parent_keys = array_keys($coll); //getting first level keys dep1,dep2 $size = sizeof($parent_keys); $flag=0; //to check if value has been found  foreach ($iter  $k=>$val) {     //if dep1 matches, record until shifts dep2     if($k === $parent_keys[$parent_index]){          $parent = $k;             //making sure counter not incremented             //more number of elements present         ($parent_index<$size-1)?$parent_index++:'';     }     if ($val == $name) {         //if value found, set flag , break loop         $flag = 1;         break;     } }  ($flag==0)?$parent='':''; //this means search string not found echo 'key = '.$parent; 

demo


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -