我有这个数组:
[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"
和另一个数组:
$new_country = array(
'gbr' => 'Great Britain',
'fra' => 'France',
'ita' => 'Italy',
'de' => 'Germany',
'esp' => 'Spain'
);
我应该在数组上运行什么确切的函数来运行$ new_country数组并生成下面的输出?
我想产生这个输出:
<h2>France</h2>
<p>Montpellier</h2>
<h2>Great Britain</h2>
<p>York</p>
<p>Hull</p>
修改
到目前为止,最好的答案产生了这个输出(国家是重复的):
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
答案 0 :(得分:2)
按国家/地区排序
usort($array,function($a,$b){
return strcmp($a['country'],$b['country']);
});
然后
$lastc="";
foreach($array as $v){
if($v['country']!=$lastc){
$lastc=$v['country'];
print "<h2>$new_country[$lastc]</h2>";
}
print "<p>".$v['title'].'<p>';
}
答案 1 :(得分:1)
分组的其他解决方案
$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>';
}
}