Reputation: 1
I believe what I'm trying to accomplish is straight forward.
Some context, the code below simple pushes a city name ($cityProx) into a single dimension array($validLocationCity) if the a given distance is less a given proximity distance($prox)
if($actualDistance <= $prox)
{
array_push($validLocationCity,$cityProx);
}
So this is fine. But now I wish to sort this array of cities based on the distance.
My theory for a simple way to accomplish this, is to store the distance as the key in the array, allowing me to use ksort(), this will allow me to loop through the cities, nearest first at a later point.
if($actualDistance <= $prox)
{
$validLocationCitySortDistance[$actualDistance] = $cityProx;
}
Above was my first attempt at accomplishing this, but, of course, any city with same distance will overwrite the previous value stored for that distance/key.
How can I implement this so that if the keys are the same, ie equal distance, the new value(city name) will simply be added/appended to that key. Also assume the distance will be equal in more than 1 case.
// End question
//--------------------------------->>
I attempted adding a new array as the value if for a given key was taken
if($validLocationCitySortDistance[$actualDistance] != null)
{
$validLocationCitySortDistance[$actualDistance] [] = $cityProx;
}
else
{
$validLocationCitySortDistance[$actualDistance] = $cityProx;
}
This appears to be an incorrect and overly complicated way to do what I'm trying to do. Since I don't know how many times I need to iterate, this method sucks. I'll admit, I think I might be just misunderstanding what exactly I'm doing in the latter example above.
If somebody could help it would really appreciated, I'd also ask if you see a quick solution to also show how I might grab the values from your solution using a foreach or the likes.
Hope you get me,
Thanks in advance!
Upvotes: 0
Views: 5685
Reputation: 144
using city names as keys and applying asort() will do the trick.
$myarr = ['delhi' => 12,
'kolkata' => 30,
'hyderabad' => 4,
'adilabad' => 1,
'vizag' => 10];
asort($myarr);
then you can access keys using
foreach($myarr as $key => $value) {
echo "{$key} : {$value}";
}
or
array_walk($myarr, function($value, $key) {
echo "{$key} : {$value} ";
});
Upvotes: 2