Search_array in nested arrays

风格不统一 提交于 2020-01-04 14:18:52

问题


I've got an array with nested arrays, and I was trying to use the *search_array* function to sift through the array and give me back their keys. It hasn't been working. Here's the code:

<?php 
$array = array(
   'cat1' => array(1,2,3),
   'cat2' => array(4,5,6),
   'cat3' => array(7,8,9),
);

foreach($array as $cat){
   if(is_array($cat)
      echo array_search(5,$cat); //want it to return 'cat2'
   else
      echo array_search(5,$array);
}

Thanks!


回答1:


If you always have a two-dimensional array, then it is as easy as:

function find($needle, $haystack) {
    foreach($haystack as $key=>$value){
       if(is_array($value) && array_search($needle, $value) !== false) {
          return $key;
       }
    }
    return false;
}

$cat = find(5, $array);



回答2:


function mySearch($haystack, $needle, $index = null)
{
    $aIt   = new RecursiveArrayIterator($haystack);
    $it    = new RecursiveIteratorIterator($aIt);   
    while($it->valid())
    {       
        if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
            return $aIt->key();
        }       
        $it->next();
    }   
    return false;
}

$array = array(
   'cat1' => array(1,2,3),
   'cat2' => array(4,5,6),
   'cat3' => array(7,8,9),
);

echo $arr_key = mySearch($array, 5); 

this will give u the answer



来源:https://stackoverflow.com/questions/4290713/search-array-in-nested-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!