note 69826 added to function.array-search

From: Date: Fri, 22 Sep 2006 12:19:08 +0000
Subject: note 69826 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-117418@lists.php.net to get a copy of this message
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) */ ?> ---- Server IP: 83.137.200.2 Probable Submitter: 217.22.16.30 (proxied: 1.1 LNH-ISA) ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/69826 Del: integrated -- https://master.php.net/note/delete/69826/integrated Del: useless -- https://master.php.net/note/delete/69826/useless Del: bad code -- https://master.php.net/note/delete/69826/bad+code Del: spam -- https://master.php.net/note/delete/69826/spam Del: non-english -- https://master.php.net/note/delete/69826/non-english Del: in docs -- https://master.php.net/note/delete/69826/in+docs Del: other reasons-- https://master.php.net/note/delete/69826 Reject -- https://master.php.net/note/reject/69826 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#117418) next »