note 13839 deleted from function.sort by cmb
| From: | cmb@php.net | Date: | Sun, 27 Oct 2019 08:34:55 +0000 |
| Subject: | note 13839 deleted from function.sort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212788@lists.php.net to get a copy of this message | ||
Note Submitter: phpdotnetNO_SPAM at electronic-strategy dot com
----
/*
Small function to Alphabetically sort Multidimensional arrays by index values of an n dimension
array.
I have only tested this for sorting an array of up to 6 dimensions by a value within the second
dimension. This code is very rough and works for my purposes, but has not been tested beyond my
needs.
Although a little clunky and not a mathematical type algorithm, it get's the job done. It
theoretically overcomes many of the problems I have seen with multidimensional arrays in that it is
possible to specify within the function, not by reference :-(, which index you wish to sort by, no
matter how many dimensions down.
call function by assigning it to a new / existing array:
$row_array = multidimsort($row_array);
*/
function multidimsort($array_in) {
$multiarray = array();
$array_out = array();
$loopvalue = 0;
/* -1 as traversal of array starts from 0, count() starts from 1 */
$multicount = count($array_in) - 1;
/* add the indexes you wish to sort array by to a new array in this case index is two levels down,
but shouldn't make a difference if it goes further indexes down. (Not tested!) */
for($i = 0; $i <= $multicount; $i++) {
array_push($multiarray, $array_in[$i][2]);
//array_push($multiarray, $array_in[$i][2][4]);
//array_push($multiarray, $array_in[$i][1][3][7]);
}
/* alphabetically sort the new array (Ascending in this case) can chage sort to whatever type you
like. Even apply user-defined sort. */
asort($multiarray);
/* reset internal pointer to beginning of array after above sort */
reset($multiarray);
/* traverse new array of index values and add the corresponding element of the input array to the
correct position in the output array */
while (list ($key, $val) = each ($multiarray)) {
$array_out[$loopvalue] = $array_in[$key];
$loopvalue++;
}
/* return the output array which is all nicely sorted by the index you wanted! */
return $array_out;
}