PHP 8.4.24 Released!

Voting

: two minus one?
(Example: nine)

The Note You're Voting On

sweetland at whoadammit dot com
25 years ago
Here's a little routine I whipped up to sort multi-dimensional arrays:
<?php
/**
 ** comesafter ($s1, $s2)
 **
 ** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
 **/

function comesafter ($s1, $s2) {
        /**
         ** We don't want to overstep the bounds of one of the strings and segfault,
         ** so let's see which one is shorter.
         **/

        $order = 1;

        if (strlen ($s1) > strlen ($s2)) {
                $temp = $s1;
                $s1 = $s2;
                $s2 = $temp;
                $order = 0;
        }

        for ($index = 0; $index < strlen ($s1); $index++) {
                /**
                 ** $s1 comes after $s2
                 **/

                if ($s1[$index] > $s2[$index]) return ($order);

                /**
                 ** $s1 comes before $s2
                 **/

                if ($s1[$index] < $s2[$index]) return (1 - $order);
        }
 
        /**
         ** Special case in which $s1 is a substring of $s2
         **/

        return ($order);
}

/**
 ** asortbyindex ($sortarray, $index)
 **
 ** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
 ** of the Ith member of both the group and user arrays is a string identifier. In the
 ** case of a user array this is the username; with the group array it is the group name.
 ** asortby
 **/

function asortbyindex ($sortarray, $index) {
        $lastindex = count ($sortarray) - 1;
        for ($subindex = 0; $subindex < $lastindex; $subindex++) {
                $lastiteration = $lastindex - $subindex;
                for ($iteration = 0; $iteration < $lastiteration;    $iteration++) {
                        $nextchar = 0;
                        if (comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index])) {
                                $temp = $sortarray[$iteration];
                                $sortarray[$iteration] = $sortarray[$iteration + 1];
                                $sortarray[$iteration + 1] = $temp;
                        }
                }
        }
        return ($sortarray);
}
?>

It's a bit long with all the comments, but I hope it helps.

<< Back to user notes page

To Top