1

我正在寻找一种解决方案,在某个字母或数字之后从排序数组中获取所有单词(或数字)。即字母K之后的所有国家。

$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);

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

但我只想要字母 K 之后的国家:立陶宛、卢森堡、马耳他、荷兰、挪威……

有任何想法吗?

4

3 回答 3

3

使用该array_filter功能过滤掉你不想要的东西。

$result = array_filter( $countries, function( $country ) {
  return strtoupper($country{0}) > "K";
});
于 2014-12-02T18:40:40.260 回答
0

你可以这样做:

$countries2 = array();
foreach ($countries as $country) {
    if(strtoupper($country[0]) > "K") break;
    $countries2[] = $country;
}
于 2014-12-02T18:59:48.917 回答
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

希望对所有想要在某事后拼接自然有序数组的人有所帮助。

于 2014-12-03T19:27:33.987 回答