note 69826 deleted from function.array-search by levim

From: Date: Mon, 24 Feb 2014 22:40:56 +0000
Subject: note 69826 deleted from function.array-search by levim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-198646@lists.php.net to get a copy of this message
Note Submitter: lars-magne ---- Further comments on the multidimensional array searches given earlier: I needed an extended search function which could search in both keys and values in any # dimension array and return all results. Each result contains key/value hit, type (key or value), key path and value (in case result is a key). <?php function array_search_ext($arr, $search, $exact = true, $trav_keys = null) { if(!is_array($arr) || !$search || ($trav_keys && !is_array($trav_keys))) return false; $res_arr = array(); foreach($arr as $key => $val) { $used_keys = $trav_keys ? array_merge($trav_keys, array($key)) : array($key); if(($key === $search) || (!$exact && (strpos(strtolower($key), strtolower($search)) !== false))) $res_arr[] = array('type' => "key", 'hit' => $key, 'keys' => $used_keys, 'val' => $val); if(is_array($val) && ($children_res = array_search_ext($val, $search, $exact, $used_keys))) $res_arr = array_merge($res_arr, $children_res); else if(($val === $search) || (!$exact && (strpos(strtolower($val), strtolower($search)) !== false))) $res_arr[] = array('type' => "val", 'hit' => $val, 'keys' => $used_keys, 'val' => $val); } return $res_arr ? $res_arr : false; } // I.e.: $haystack[754] = "Norwegian"; $haystack[28]['details']['Norway'] = "Oslo"; $needle = "Norw"; if($results = array_search_ext($haystack, $needle, false)) foreach($results as $res) echo "Found '$needle' in $res[type] '$res[hit]', using key(s) '".implode("', '", $res['keys'])."'. (Value: $res[val])<br />\n"; /* Printed result will be: Found 'Norw' in val 'Norwegian', using key(s) '754'. (Value: Norwegian) Found 'Norw' in key 'Norway', using key(s) '28', 'details', 'Norway'. (Value: Oslo) */ ?>

« previous php.notes (#198646) next »