note 99907 deleted from function.array-search by danbrown

From: Date: Tue, 14 Sep 2010 15:15:56 +0000
Subject: note 99907 deleted from function.array-search by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-172549@lists.php.net to get a copy of this message
Note Submitter: halio11 ---- recursive array_search function.... /** * makes a recursive array search and returns a string array, with flat key navigation to all matches * @param mixed $needle * @param mixed array $haystackarray * @param boolean $strict * @param boolean $rootLvl * @param string $keySep * @return string array */ function array_search_recursive($needle, array $haystackarray, $strict = false, $keySep = '=>', $rootLvl = true) { $ret = array(); foreach($haystackarray as $key => $item) { //checks if item is equal to needle if(!is_array($item) && (($strict && $item === $needle) || (!$strict && $item == $needle))) { $ret[]['field'] = $key; } elseif(is_array($item)) { //if item is an array, make recursive call with item as $haystackarray $res = array_search_recursive($needle, $item, $strict, $keySep, false); if($res) { $ret[] = array( 'field' => $key, 'childs' => $res ); } } } if($rootLvl) { //if root level, make a string array to return _get_array_search_result($ret, $realRet, $keySep); $ret = $realRet; } return $ret; } /** * parses array_search_recursive result array into a string array * @param mixed array $resArray * @param string array $res * @param string $keySep * @param integer $parent */ function _get_array_search_result($resArray, &$res = '', $keySep = '=>', $parent = 0) { $count = $parent; $parent = isset($res[$parent]) ? $res[$parent] : ''; foreach($resArray as $key => $item) { if(isset($res[$count]) && isset($item['childs']) && is_array($item['childs']) && count($item['childs']) > 1 && $key > 0) { //make a copy of parent data if more then one child exists while(isset($res[$count])) { $count++; } } if(isset($item['childs']) && is_array($item['childs'])) { //if childs field is an array make recursive call with childs as $resArray $res[$count] = (empty($parent) ? '' : $parent.$keySep).$item['field']; $res[$count] .= _get_array_search_result($item['childs'], $res, $keySep, $count); } else { $res[$count] = (empty($parent) ? '' : $parent.$keySep).$item['field']; } $count++; } } example: $array = array( '1_1' => array( '2_1' => array( '3_1' => 'value1' ), '2_2' => 'value2' ), '1_2' => array( '2_3' => array( '3_2' => 'value3' ), '2_4' => 'value4' ), '1_3' => array( '2_5' => 'value5' ), '1_4' => array( '2_6' => 'value1' ) ); print_r(array_search_recursive('value1', $array)); print_r(array_search_recursive('value2', $array, true, ' | ')); output: Array ( [0] => 1_1=>2_1=>3_1 [1] => 1_4=>2_6 ) Array ( [0] => 1_1 | 2_2 )

« previous php.notes (#172549) next »