PHP group/sort an array by 3 letter country code
I have this array:
[1]=>
array(4) {
["id"]=>
string(2) "31"
["slug"]=>
string(11) "montpellier"
["title"]=>
string(11) "Montpellier"
["country"]=>
string(3) "fra"
}
[2]=>
array(4) {
["id"]=>
string(2) "30"
["slug"]=>
string(4) "york"
["title"]=>
string(4) "York"
["country"]=>
string(3) "gbr"
}
[3]=>
array(4) {
["id"]=>
string(2) "29"
["slug"]=>
string(4) "hull"
["title"]=>
string(4) "Hull"
["country"]=>
string(3) "gbr"
and this other array:
$new_country = array(
'gbr' => 'Great Britain',
'fra' => 'France',
'ita' => 'Italy',
'de' => 'Germany',
'esp' => 'Spain'
);
What exact function should i run on the array to run it through the $new_country array and produce the output below?
I'd like to produce this output:
<h2>France</h2>
<p>Montpellie开发者_运维知识库r</h2>
<h2>Great Britain</h2>
<p>York</p>
<p>Hull</p>
EDIT
The best answer so far produces this output (countries are duplicated):
Great Britain
Durham
France
Montpellier
Great Britain
York
Hull
Bradford
Leeds
Germany
Berlin
Great Britain
Leicester
Colchester
Oxford
Nottingham
Newcastle
St. Andrews
Loughborough
Chester
Ipswich
Bangor
Wolverhampton
Liverpool
Italy
Rome
Great Britain
Dundee
Sheffield
Bristol
Birmingham
Spain
Madrid
Barcelona
France
Paris
Great Britain
London
Manchester
Edinburgh
Italy
Turin
Great Britain
Glasgow
Sort by country
usort($array,function($a,$b){
return strcmp($a['country'],$b['country']);
});
then
$lastc="";
foreach($array as $v){
if($v['country']!=$lastc){
$lastc=$v['country'];
print "<h2>$new_country[$lastc]</h2>";
}
print "<p>".$v['title'].'<p>';
}
Other solution with grouping
$newarr=array();
foreach($array as $v){
$newarr[$v['country']][]=$v;
}
foreach($new_country as $k=>$v){
if(isset($newarr[$k])){
print '<h2>'.$v.'</h2>';
foreach($newarr[$k] as $town)
print '<p>'.$town['title'].'</p>';
}
}
精彩评论