S
S
Sasha Brahms2015-11-06 22:59:16
PHP
Sasha Brahms, 2015-11-06 22:59:16

How to search in a multidimensional array (my version)?

How do you like my version?
I wanted to do without
$out_index[] = $key;
it, but I couldn't figure out how...
Here's the actual code:

function array_search_recursive($needle, array $haystack){
  $out_index = array();
  
  foreach($haystack as $key => $value){
    if(is_array($value)){
      $out_index[] = $key;
      $out_index[] = array_search_recursive($needle, $value);
 		}
  }
  return (empty($out_index))? array_search($needle, $haystack) : $out_index;
}

execution example:
Source array:
$arr = array('one' => 1,
       'two' => array(
              'oone'   => 'mda',
              'ttwwoo' => 'YO!'
              )
      );

Next:
var_dump(array_search_recursive('mda',$arr));
Result:
array(2) {
  [0]=>
  string(3) "two"
  [1]=>
  string(4) "oone"
}

What do you think, normal or not?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
inDeepCode, 2015-11-06
@inDeepCode

$arr = array(
       'index1_level1' => array(
            'index1_level2' => array(
                'index1_leve3' => 'YO!'
            )
        ),
        'index2_level1' => array(
            'index2_level2' => 'YO!',
            'index2_level2_1' => array(
                'index2_level3' => 'YO!'
            )
        )
);
      
print_r(array_search_recursive('YO!',$arr));

Array ( 
    [0] => index1_level1 
    [1] => Array ( 
        [0] => index1_level2 
        [1] => index1_leve3 
    ) 
    [2] => index2_level1 
    [3] => Array ( 
        [0] => index2_level2_1 
        [1] => index2_level3 
    ) 
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question