Reputation: 137
Given the following PHP array:
Array
(
[0] => Array
(
[name] => Restaurant 123
[city] => Arlington
[zip] => 22201
)
[1] => Array
(
[name] => Bar Foo
[city] => Ballston
[zip] => 22201
)
[2] => Array
(
[name] => Restaurant XYZ
[city] => Ballston
[zip] => 22201
)
[3] => Array
(
[name] => Restaurant 321
[city] => Washington DC
[zip] => 22201
)
)
How can I produce a list sorted according to city (alphabetically), so that it would output something like:
Arlington
Restaurant 123
Ballston
Bar Foo
Restaurant XYZ
Washington DC
Restaurant 321
E.G., sorted first by city name alphabetically, and then by venue name, also alphabetically. Also note that it's not given that the restaurant name, nor the cities are alphabetically sorted in the array given.
Upvotes: 2
Views: 1796
Reputation: 16768
Looks like theres two parts to what you want - sorting and displaying.
To sort, you want to use usort
with small function defining the comparison
$sortFunc = function($a,$b) {return $a['city'] != $b['city']
? $a['city'] > $b['city']
: $a['name'] > $b['name'];};
// = function($a,$b) {return $a['city'] > $b['city'] || ($a['city'] == $b['city'] && $a['name'] > $b['name']);};
// = function($a,$b) {return 100*strcmp($a['city'],$b['city']) + strcmp($a['name'],$b['name']);};
usort($arr, $sortFunc);
function displayNamesGroupedByCity($arr)
{
$lastCity = '';
foreach($arr as $v)
{
if ($v['city'] != $lastCity)
{
$lastCity = $v['city'];
echo "<br /><strong>$lastCity</strong><br />";
}
else echo ', ';
echo $v['name'];
}
}
displayNamesGroupedByCity($arr);
For the hell of it im going to make things generic
function displayXgroupedByY($arr, $x, $y)
{
$sortFunc = function($a,$b) use($x,$y)
{return $a[$y] != $b[$y]
? $a[$y] > $b[$y]
: $a[$x] > $b[$y];};
user($arr, $sortFunc);
$lastCity = '';
foreach($arr as $v)
{
if ($v['city'] != $lastCity)
{
$lastCity = $v['city'];
echo "<br /><strong>$lastCity</strong><br />";
}
else echo ', ';
echo $v['name'];
}
return $arr;
}
displayXGroupedByY($arr, 'name', 'city');
Upvotes: 1
Reputation: 25564
user defined sorting should do a work:
https://www.php.net/manual/en/function.uasort.php
Upvotes: 1
Reputation: 6131
Try usort ( http://php.net/manual/en/function.usort.php ) where you can define a custom sort schema like
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
Upvotes: 2
Reputation: 91299
You can use usort
, which enables you to sort an array based on a user-defined comparison function.
Upvotes: 2