Sorting an Array - CSORT
- From: "Nel" <nelly@xxxxxxxxxxxxxxxx>
- Date: Mon, 28 Nov 2005 20:19:01 -0000
Hi all,
I am using php and mysql to search through a database of stores for the
nearest store to a given postcode.
I have managed to limit the selection to the nearest stores (roughly within
a given area), but once I have the array from mysql I need to do a
calculation to find the number of miles in between the store and the user's
postcode ($distance). I can do this by looping through the array.
Finally I need to sort the array by $distance, ASC. This is where I am
failing. I have read the FM and Googled. The best result is the one below
which seemed to do what I needed in terms of the search, but it gives an
error on the line
foreach($array as $row) {
Not sure why?
I am using PHP Version 4.3.8 on Windoze.
Nel.
_______________________________________________
POST FROM 2004 comp.lang.php
_______________________________________________
You can use array_multisort() to create a kind of column sort function:
function csort($array, $column) {
$s = array();
foreach($array as $row) {
$s[] = $row[$column];
}
array_multisort($s, SORT_ASC, $array);
return $array;
}
Example:
$foo = array(
array('firstname' => 'foo', 'lastname' => 'bar'),
array('firstname' => 'bar', 'lastname' => 'foo')
);
print_r(csort($foo, 'firstname'));
Output:
Array
(
[0] => Array
(
[firstname] => bar
[lastname] => foo
)
[1] => Array
(
[firstname] => foo
[lastname] => bar
)
)
HTH
Micha
.
- Follow-Ups:
- Re: Sorting an Array - CSORT
- From: Ewoud Dronkert
- Re: Sorting an Array - CSORT
- Prev by Date: Re: PHP/HTML displays garbage ...
- Next by Date: Re: PHP/HTML displays garbage ...
- Previous by thread: Re: what 's wrong of the syntax
- Next by thread: Re: Sorting an Array - CSORT
- Index(es):
Relevant Pages
|