Page 1 of 1

sorting an array

Posted: Wed May 14, 2003 6:18 am
by FredEH
Hi,

I've been searching all over for how to do this. I read the online docs from php.net and they are kinda tough to understand. Here's a sample of what my code kinda looks like:

Code: Select all

<?php
$array1 = array();
while($myrow = mysql_fetch_array($result))
{
  $array2 = array(
      "num1" => myrow['num1'],
      "num2" => myrow['num2'],
      "num3" => myrow['num3'],
      "num4" => myrow['num4']
   );
  $array1[$i] = $array2;
  $i++;
}
?>
I need to be able to sort $array1 by say "num3" so that it would output something like:

Code: Select all

Array1&#1111;0] is 1, 2, 5, 0
Array1&#1111;1] is 1, 2, 4, 0
Array1&#1111;2] is 1, 2, 3, 0
Array1&#1111;3] is 1, 2, 2, 0
Can anyone help me with this? I hope this is clear enough. I would greatly appreciate it :)

Posted: Wed May 14, 2003 6:28 am
by []InTeR[]
I think the function you are looking for is multisort

Posted: Wed May 14, 2003 6:28 am
by Gleeb
You could change your SQL to sort it for you. Is there some reason you can't? Don't forget, unless you're dealing with vast amounts of data, multiple calls to the database should be fast enough.

Posted: Wed May 14, 2003 7:01 am
by FredEH
[]InTeR[] wrote:I think the function you are looking for is multisort
That worked. Thanks.
You could change your SQL to sort it for you. Is there some reason you can't? Don't forget, unless you're dealing with vast amounts of data, multiple calls to the database should be fast enough.
Sorry, I should have specified that the value of the element that I want to sort by is calculated from fields that are pulled from the database. That's why I couldn't ORDER BY.

Thanks for the help! :)

Posted: Wed May 14, 2003 7:25 am
by FredEH
One more thing,

I once saw a tutorial (i can't find it again :evil: ) that showed how to create an html table with links for each column header that would sort the table by that field when clicked.

Anyone know where I can find this tutorial?

Thanks again

Posted: Wed May 14, 2003 7:40 am
by []InTeR[]
Just make a GET value like 'sort'

Code: Select all

&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;&lt;a href="?sort=id"&gt;id&lt;/a&gt;&lt;/th&gt;
    &lt;th&gt;&lt;a href="?sort=name"&gt;name&lt;/a&gt;&lt;/th&gt;
  &lt;/tr&gt;
enz....
and in your php

Code: Select all

<?
  $order = (isset($_GET["sort"])? $_GET["sort"] : "id";
  $query = "SELECT * FROM users ORDER BY ".$order;
?>

Posted: Wed May 14, 2003 7:57 am
by FredEH
Thanks :D

Posted: Thu May 15, 2003 3:42 am
by pok
:D Goods

Posted: Thu May 15, 2003 3:44 am
by []InTeR[]
Thanks for the Thanks :lol: