...

View Full Version : Sorting an array/foreach statement



robbiez
02-18-2010, 12:37 PM
Bit of a novice - sorry.

I have a script that includes a foreach statement

foreach($products as $i => $f)

The products are then printed into a table.

$f is an array of variables obtained from the database. Currently it is sorted by the $f[id] value. I presume this is by default as there is no logic in the script for sorting the array.

How can I sort $f by one of the other values, such as $[price]

Thanks
Rob

DaiWelsh
02-18-2010, 02:00 PM
The best way would be to modify the query that originally fills this array so that it fills it in the correct order. If that is not possible there are functions for sorting arrays with a user-defined sort function, see http://www.php.net/usort and particularly example #2

HTH,

Dai

Fou-Lu
02-18-2010, 02:00 PM
The easiest way would be to just sort you're SQL when you're querying it.
Aside from that, write a comparator and run it through a sort:


function cmp($a, $b)
{
return $a['price'] - $b['price'];
}

uasort($products, 'cmp');
foreach ($products AS $i => $f)
{
.....

DaiWelsh
02-18-2010, 02:18 PM
lol, same server time, but mine came first, so do I win, or are we both jinxed? :)

Fou-Lu
02-18-2010, 02:21 PM
o.O
I got chown'd :D

robbiez
02-18-2010, 02:45 PM
Thanks to both you. It has sorted my problem.

Would it be possible to point me in the right direction to take it one step further.

How would I go about implementing search options:
Lowest Price First|Smallest item First , etc.

I am not sure how to call an PHP function using an onclick event - is that even possible?? or will I have to use javascript??

Rob

DaiWelsh
02-18-2010, 02:52 PM
You could do a javascript sort using AJAX to reload the data from the server and repopulate the table (or even do the sort within javascript) but more normally you would make the sort link reload the page from the server and then make the sort order field in the SQL query depend on the variable passed e.g.

results.php?sort=price
results.php?sort=size

and then in your PHP check $_GET['sort'] and choose the sort field in the SQL query accordingly. If you are paginating or filtering or for some other reason need to retain more variables it gets more complex, then you can either tack all necessary vars to rebuild the results onto the url or probably simpler keep the results state in session and only change the sort order then regenerate when they click the link.

HTH,

Dai



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum