[thelist] PHP 2D array sort

Michael Pemberton mpember at phreaker.net
Tue May 21 07:40:00 CDT 2002


Bigpant wrote:

>I am trying to sort a 2 dimensional array in PHP.
>
>$a = array(array (
>			"text" => "",
>			"qty" => 0
>			));
>$a['text'][0] = "two";
>$a['qty'][0] = 2;
>
>$a['text'][1] = "one";
>$a['qty'][1] = 1;
>
>I want to order $a['text'] by $a['qty'], but the sort functions don't
>appear to have facility for this. Do I have to build my own bubble sort?
>
>TIA
>Phil
>
>
>
I put together somthing a while back that performed this type of thing.
 Here's the code:

    function customCompare ($one, $two) {
        if ($one["GLS"] > $two["GLS"]) return -1;
        if ($one["GLS"] < $two["GLS"]) return 1;
        if ($one["BHS"] > $two["BHS"]) return -1;
        if ($one["BHS"] < $two["BHS"]) return 1;
        if ($one["KCK"] > $two["KCK"]) return -1;
        if ($one["KCK"] < $two["KCK"]) return 1;
        if ($one["HBL"] > $two["HBL"]) return -1;
        if ($one["HBL"] < $two["HBL"]) return 1;
        if ($one["MRK"] > $two["MRK"]) return -1;
        if ($one["MRK"] < $two["MRK"]) return 1;
        return 0;
    };

    usort ($newdata, "customCompare");

By returning a value of -1 to indicate a lesser result, a +1 to indicate
a greater result and a 0 to indicate an equal result, you can test the
values using what ever formulas you want.

If you have any further questions, don't hesitate to stick you hand in
the air.

--
Michael Pemberton
mpember at phreaker.net
ICQ: 12107010








More information about the thelist mailing list