note 46254 deleted from function.array-multisort by nlopess

From: Date: Mon, 04 Oct 2004 17:32:09 +0000
Subject: note 46254 deleted from function.array-multisort by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-77995@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); //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; } } } ?>

« previous php.notes (#77995) next »