note 46255 deleted from function.array-multisort by aidan

From: Date: Wed, 06 Oct 2004 06:53:11 +0000
Subject: note 46255 deleted from function.array-multisort by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-78059@lists.php.net to get a copy of this message
Note Submitter: duerra at NOTTHIS dot pushitlive dot NOTTHIS dot net ---- Unfortunately, array_multisort doesn't allow you to use the natural sorting algorithm for multi-dimensional sorting. To combine my needs for recursively sorting a two+ dimensional array by a key name, and the need to use natural sorting algorithms, I developed a flexible solution to sorting a multi-dimensional array by key name. <?php //Extra definition for sorting using natural sort algorithm define('SORT_NATURAL', 3); //Example $sortArr = array(); $sortArr[] = array('file' => 'my file.txt', 'dir' => '/path/to/dir'); $sortArr[] = array('file' => 'anotherfile.exe', 'dir' => '/path/to/dir'); $sortArr[] = array('file' => 'YAF file.log', 'dir' => '/path/to/dir'); $sortArr[] = array('file' => 'a small file.txt', 'dir' => '/path/to/dir'); array_key_multisort($sortArr, 'file'); print_r($sortArr); //Sort "key" through multidimensional array recursively function array_key_multisort(&$sourceArray, $key, $sortType = SORT_NATURAL, $sortOrder = SORT_ASC, $nullVal=false) { if(!is_array($sourceArray)) { return; } $sortVals = array(); $keyExists = false; foreach ( $sourceArray as $arrKey => $arrRow ) { foreach($arrRow AS $rowKey => $rowVal) { //Loop next dimension if row is an array if(is_array($rowVal)) { array_key_multisort($sourceArray[$arrKey], $key, $sortType, $sortOrder, $nullVal); } } //If the key we're searching for is set, add it to the sort-by array if(isset($arrRow[$key])) { $keyExists = true; $sortVals[] = $arrRow[$key]; } else { $sortVals[] = $nullVal; } } //Only sort if the key existed if($keyExists) { if($sortType == SORT_NATURAL) { natcasesort($sortVals); //natcasesort does not accept sort-order flags if($sortOrder == SORT_DESC) { array_reverse($sortVals); } } else { asort($sortVals, $sortType, $sortOrder); } //Rearranging the sourceArray by the new order $retArr = array(); foreach($sortVals AS $key=>$value) { $retArr[] = $sourceArray[$key]; } foreach($retArr AS $key=>$val) { $sourceArray[$key] = $val; } } } ?> Outputs: Array ( [0] => Array ( [file] => anotherfile.exe [dir] => /path/to/dir ) [1] => Array ( [file] => a small file.txt [dir] => /path/to/dir ) [2] => Array ( [file] => my file.txt [dir] => /path/to/dir ) [3] => Array ( [file] => YAF file.log [dir] => /path/to/dir ) )

« previous php.notes (#78059) next »