Link to home
Start Free TrialLog in
Avatar of previewservices
previewservicesFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Sorting values from multiple arrays

Hello,

In PHP, i am getting 3 values from a DB and putting them into an array. They are ID, Title and Distance. The distance is being calculated in PHP because it is longitude and latitude. I am then sorting using asort() on the arrayDistance however this doesn't sort the ID and Title at the same time if you get what i mean. I need it so take all 3 arrays and sort by arrayDistance. Sorting arrayDistance alone muddles up the other arrays and no longer can i do $arrayTitle[0] $arrayID[0] and $arrayDistance[0].

Thanks in advance.
$i=0;
while ($i < $num) {
	$near_title=mysql_result($result,$i,"title");
	$near_long=mysql_result($result,$i,"Longitude");
	$near_lat=mysql_result($result,$i,"Latitude");
	$near_id=mysql_result($result,$i,"ID");
	
	$arrayTitle[$i]=$near_title;
	$arrayID[$i]=$near_id;
	$arrayDistance[$i]=round(distance($spot_lat, $spot_long, $near_lat, $near_long, "m"), 1);
$i++;
}

asort($arrayDistance);

Open in new window

Avatar of te-edu
te-edu
Flag of Serbia image

$i=0;
$array = array();
while ($i < $num) {
	$near_title=mysql_result($result,$i,"title");
	$near_long=mysql_result($result,$i,"Longitude");
	$near_lat=mysql_result($result,$i,"Latitude");
	$near_id=mysql_result($result,$i,"ID");
	
	$array[$i]['title']=$near_title;
	$array[$i]['id']=$near_id;
	$array[$i]['distance']=round(distance($spot_lat, $spot_long, $near_lat, $near_long, "m"), 1);
$i++;
}

asort($array);

Open in new window


Accessing:
$array[0]['title'] = 
$array[0]['id'] = 
$array[0]['distance'] = 

Open in new window

Avatar of previewservices

ASKER

Okay thanks. But where do i say sort by distance?  I only see asort($array);
Make an array of objects.  Use the distance as the keys and you can use ksort() to sort the data.
Have you got an example please?

$distance = round(distance($spot_lat, $spot_long, $near_lat, $near_long, "m"), 1);

$array[$i][$distance]['distance']=$distance;
$array[$i][$distance][title]=$near_title;
$array[$i][$distance]['id']=$near_id;

ksort($array);

Open in new window


ASKER CERTIFIED SOLUTION
Avatar of mattibutt
mattibutt
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial