Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 1.72 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. PHP looping multidimensional array
  2. function loop($arr, $find) {
  3.   for($i=0;$i<count($arr);$i++) {
  4.     if($arr[$i] == $find) {
  5.       print "Found $find";
  6.       return true;
  7.     } else {
  8.       if(is_array($arr[$i])) {
  9.          $this->loop($arr[$i], $find);
  10.       } else {
  11.          print "Couldn't find $find";
  12.          return false;
  13.       }
  14.     }
  15.    }
  16.  }
  17.        
  18. var $found = false;
  19. function loop($arr, $find) {
  20.   foreach($arr as $k=>$v){
  21.     if($find==$v){
  22.       $this->found = true;
  23.     }elseif(is_array($v)){
  24.       $this->loop($v, $find);
  25.     }
  26.   }
  27.   return $this->found;
  28. }
  29.        
  30. function array_search_key( $needle_key, $array ) {
  31.   foreach($array AS $key=>$value){
  32.     if($key == $needle_key) return $value;
  33.     if(is_array($value)){
  34.       if( ($result = array_search_key($needle_key,$value)) !== false)
  35.         return $result;
  36.     }
  37.   }
  38.   return false;
  39. }
  40.        
  41. function loop($arr, $find) {
  42.     for($i=0;$i<count($arr);$i++) {
  43.         if(is_array($arr[$i])) {
  44.             $this->loop($arr[$i], $find);
  45.         } else {
  46.             if($arr[$i] == $find) {
  47.                 print "Found $find";
  48.                 return true;
  49.             }
  50.         }
  51.     }
  52.     return false;
  53. }
  54.        
  55. class ArraySearch
  56.     {
  57.          public $needle;
  58.          public $found;
  59.  
  60.          public function Find($value, $key)
  61.          {
  62.               if ($this->needle == $value)
  63.                    $this->found = true;
  64.          }
  65.     }
  66.  
  67.     //test data of nested array
  68.     $sweet = array('a' => 'apple', 'b' => 'banana');
  69.     $fruits = array('sweet' => $sweet, 'sour' => 'lemon');
  70.  
  71.     // search for banana
  72.     $searcher = new ArraySearch();
  73.     $searcher->needle = "banana";
  74.     array_walk_recursive($fruits, array($searcher, 'Find'));
  75.  
  76.     // print result
  77.     echo('result = '.$searcher->found);