Sorting an Array - CSORT



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


.



Relevant Pages

  • Re: Advice about fetching user information
    ... but actually *selecting* them in MySQL ... PHP scripts and use a gaugefunction to time pretty much every ... The same is pretty much true for searching an array in PHP - ... But I wouldn't be searching. ...
    (comp.lang.php)
  • Re: Using DBI, better option than importing into @array
    ... MySQL, though, so I'm having fun with the challenges along the way. ... importing the subjects table into an array in the beginning of the ... is not a good measurement. ... That's extremely helpful, Peter. ...
    (comp.lang.perl.misc)
  • Re: [PHP] Add New Records Only!
    ... I do understand getting data from both the existing DBF and the multiple ... mySQL tables into a temporary mySQL table. ... Then, in the receiving code, have an array of SQL connections. ... Save a copy of your primary key for each next ...
    (php.general)
  • Re: Using DBI, better option than importing into @array
    ... MySQL, though, so I'm having fun with the challenges along the way. ... importing the subjects table into an array in the beginning of the ... and you'll probably guess wrong and spend a lot of time improving ... my @filenames; ...
    (comp.lang.perl.misc)
  • php/mysql puzzler
    ... wrapper function I've written to insert an array in a table. ... What is weirder is that it works fine on my local server -- I only get ... php or mysql setting that may have unintended consequence elsewhere. ...
    (comp.lang.php)