Sort and display array values according to a value?
Given the following PHP array:
Array
(
[0] => Array
(
[name] => Restaurant 123
[city] => Arlington
[zip] => 22201
)
[1] => Array
(
[name] => Bar Foo
[city] => Ballston
[zip] => 22201开发者_StackOverflow社区
)
[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.
Write a callback function that you can pass to usort, for example
function compare_venues($a, $b)
{
return strcmp($a['name'], $b['name']);
}
You can use usort
, which enables you to sort an array based on a user-defined comparison function.
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;
}
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');
user defined sorting should do a work:
http://us2.php.net/manual/en/function.uasort.php
精彩评论