2014-12-02 113 views
1

我正在寻找一种解决方案,以获得一个字母或数字后排序的数组中的所有单词(或数字)。即信毕竟国家K.PHP - 拼音数组按字母顺序后的一些字母

$countries = array(
'Luxembourg', 
'Germany', 
'France', 
'Spain', 
'Malta', 
'Portugal', 
'Italy', 
'Switzerland', 
'Netherlands', 
'Belgium', 
'Norway', 
'Sweden', 
'Finland', 
'Poland', 
'Lithuania', 
'United Kingdom', 
'Ireland', 
'Iceland', 
'Hungary', 
'Greece', 
'Georgia' 
); 

sort($countries); 

,将返回比利时,芬兰,法国,格鲁吉亚,德国,希腊,匈牙利,冰岛,爱尔兰,意大利,立陶宛,卢森堡,马耳他,荷兰,挪威,...

但我只希望KTER后的国家:立陶宛,卢森堡,马耳他,荷兰,挪威......

任何想法?

回答

3

使用array_filter函数来过滤掉你不想要的东西。

$result = array_filter($countries, function($country) { 
    return strtoupper($country{0}) > "K"; 
}); 
+0

请注意,匿名函数仅适用于PHP 5.3+。 http://php.net/manual/en/functions.anonymous.php – 2014-12-02 18:42:17

+0

嗯..返回一个空数组? – user3107747 2014-12-02 18:58:32

+0

使用'strtoupper'并将其与大写字母进行比较,或使用小写字母进行比较。 – AbraCadaver 2014-12-02 19:41:47

0

你可以这样做:

$countries2 = array(); 
foreach ($countries as $country) { 
    if(strtoupper($country[0]) > "K") break; 
    $countries2[] = $country; 
} 
+0

接近。如果数组中有像2014_12_02或2014_11_30这样的数字,该怎么办? 2014_12_01之后是否有可以分开所有的选项? – user3107747 2014-12-02 20:17:15

0

我终于找到一个简单的解决方案,以接续任何分隔符之后的数组。即使它不是字母或数字(如“2013_12_03”)。只需插入通缉分隔成数组,然后顺序,然后拼接:

//dates array: 
$dates = array(
'2014_12_01_2000_Jazz_Night', 
'2014_12_13_2000_Appletowns_Christmas', 
'2015_01_24_2000_Jazz_Night', 
'2015_02_28_2000_Irish_Folk_Night', 
'2015_04_25_2000_Cajun-Swamp-Night', 
'2015_06_20_2000_Appeltowns_Summer_Session' 
); 

date_default_timezone_set('Europe/Berlin');//if needed 
$today = date(Y."_".m."_".d);//2014_12_03 for delimiter (or any other) 
$dates[] = $today;//add delimiter to array 
sort($dates);//sort alphabetically (with your delimiter) 


$offset = array_search($today, $dates);//search position of delimiter 
array_splice($dates, 0, $offset);//splice at delimiter 
array_splice($dates, 0, 1);//delete delimiter 
echo "<br>next date:<br>".$dates[0];//array after your unique delimiter 

希望帮助所有谁想要的东西拼接后自然有序阵列。