Jump to content

sorting multidimensional array


jingo_man

Recommended Posts

hi,

 

i have read the documentation around the array_multisort() function.

 

this however seems to sort horizontally, where as i need to do so vertically. does anyone know how to get around this?

 

for example, array_multisort() will work with this array:

(0,0) = A

(0,1) = B

(0,2) = C

(0,3) = D

(1,0) = E

(1,1) = F

(1,2) = G

(1,3) = H

 

so it structurally looks like:

A B C D

E F G H

 

my array, however is:

Hole1, Score1

Hole2, Score2

 

and i need to sort the "Score" column...

 

many thanks for any help.

 

jingo_man

 

Link to comment
https://forums.phpfreaks.com/topic/53424-sorting-multidimensional-array/
Share on other sites

thanks for the heads up, wildbug.

 

using your code as a base, and searching around it, i amended it slightly to work with a more advanced array.

 

i am now intending to create the compare() function to accept an extra parameter so i can check other values.

 

the function is:

function compare($a, $b)

{

    if ($a == $b) {

        return 0;

    }

    return ($a[25] < $b[25]) ? -1 : 1;

}

 

the array sorting is called with "ucase($array,"compare");

 

-----

 

i would like to change it so the number 25 (column no of the array) can be changed. thought i could add a 3rd parameter to compare() and specify which column i am after, but i cant interpret how $a and $b get their values - "compare" isnt a typical function call with parameters...

 

thanks again...

 

jingo_man

 

<?php
function compare($a, $b)
{
    global $sortcol;
    if ($a[$sortcol] == $b[$sortcol]) {
        return 0;
    }
    return ($a[$sortcol] < $b[$sortcol]) ? -1 : 1;
}

// the array sorting is called with 

$sortcol = 25;
usort($array,"compare");
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.