S
S
Sasha Brahms2015-11-08 15:03:25
PHP
Sasha Brahms, 2015-11-08 15:03:25

Multidimensional array search based on array_search?

Did a search:

function array_search_recursive($needle, array $haystack){
  $out_index = array();
  $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:
$arr = array('rest' => 1,
       'lvl_one' => array(
              'lvl_two' => array(
                      'lvl_three' => array('general' => 'mda'),
                      'rest_two'  => 'mdo'),
              'rest_three'  => 'YO!'
              )
    );
echo '<pre>';
var_dump(array_search_recursive('mda',$arr));
echo '</pre>';

Result:
array(2) {
  [0]=>
  string(7) "lvl_one"
  [1]=>
  array(2) {
    [0]=>
    string(7) "lvl_two"
    [1]=>
    array(2) {
      [0]=>
      string(9) "lvl_three"
      [1]=>
      string(7) "general"
    }
  }
}

How to fix, tell me please?
It is necessary that the result be: a one-dimensional array of the form:
lvl_one
lvl_two
lvl_three
general

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question