You are here: Sorting an Array - CSORT « PHP Programming Language « IT news, forums, messages
Sorting an Array - CSORT

Posted by Nel on 11/28/05 22:19

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

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация