Forum Moderators: coopster

Message Too Old, No Replies

Sorting a multi-dimension array

         

Nutter

11:59 pm on Jul 10, 2005 (gmt 0)

10+ Year Member



I have an array being filled with filenames like this...

$var[key][#][fullsize]
$var[key][#][thumbnail]
$var[key][#][description]
$var[key][#][filename]

How can I sort so that the numbers are sorted by [filename]?

Or, is there an equivalent function in PHP 4 to the PHP5 scandir function? That seems that it would work as well.

mogenshoj

12:16 am on Jul 11, 2005 (gmt 0)

10+ Year Member



You need to use array_multisort. Not really sure how it works, haven't had any use for it yet.

Try searching for it in the php manual

Nutter

12:41 am on Jul 11, 2005 (gmt 0)

10+ Year Member



array_multisort() is what I'm looking at right now, but I'm fairly confused. It looks like it'll sort on the number and leave the rest intact, but not do what I'm after.

mogenshoj

1:05 am on Jul 11, 2005 (gmt 0)

10+ Year Member



Try this, if should work. Put comments in the code. A work-around for multisort.
-------

// Set what to order by
$order = "vari1";
$order_type = "desc";

// Get all the data into arrays and put a counter on it
$count = 0;
while(some thing here) {
$ar1[] = array('variable1' => $row[variable_1], 'variable2' => $row[variable_2]);
$count++;
}

// function to use for sort by variable1 asc
function variable1($a, $b) {
if ($a['variable1'] > $b['variable1']) { return 1; }
if ($a['variable1'] = $b['variable1']) { return 0; }
return -1;
}

// some for variable2
function variable2($a, $b) {
if ($a['variable2'] > $b['variable2']) { return 1; }
if ($a['variable2'] = $b['variable2']) { return 0; }
return -1;
}

// Check which one to execute and use the function above in usort, reverse array if "desc" is in $order_type
if ($order == "vari1") {
usort($ar1, "variable1");
if ($order_type == "desc") {
$ar1 = array_reverse($ar1);
}
}

if ($order == "vari2") {
usort($ar1, "variable2");
if ($order_type == "desc") {
$ar1 = array_reverse($ar1);
}
}

while ($count!= 0) { // put all the variables in a new variable using the counter

$vari1 .= "$ar1[$count]['variable1'];<br>";
$vari2 .= "$ar1[$count]['variable2'];<br>";

$count--;
}

// print them down here somewhere or whatever you want

---------

Nutter

11:22 am on Jul 11, 2005 (gmt 0)

10+ Year Member



Wow, maybe I should have checked back sooner. What I wound up doing - and got working - is to put the files into a temp array, sort that array, then stick that array into the main array.

Thanks for the help,
- Ryan