输入数组
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
此处,用户Veronica
和Alex
会重复两次。即使两个用户的数量相同,即Veronica => 2, Alex => 2
,只有Veronica
将显示为输出字符串,我如何按字母顺序对数组进行排序。
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
$userCnt = array_count_values($userArr);
foreach ($userCnt as $key => $val) {
echo "$key = $val\n";
}
输出:
Veronica
答案 0 :(得分:0)
您的输入数组:
arsort($userArr);
print_r($userArr);
数组计数:
{{1}}
反转数组:
{{1}}
答案 1 :(得分:0)
试试这个:
$userArr = array(
"0"=>"Veronica",
"1"=>"Alex",
"2"=>"Joe",
"3"=>"Alex",
"4"=>"Veronica");
//below line will first create an associative array with
//values as keys and their count as the value...
$arrayVals = array_count_values($userArr);
//next we sort this array in reverse alphabetically...
krsort($arrayVals);
//finally, print it :)
print_r($arrayVals);
//will print...
Array
(
[Veronica] => 2
[Joe] => 1
[Alex] => 2
)
更新:基于OP的解释,我认为他想要数组中“最后”字母词的值。如果是这种情况,以下代码应该可以解决问题:
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
rsort($userArr);
echo current($userArr);
答案 2 :(得分:0)
使用您的方法,我假设您希望计数最高的那个也是按字母顺序排列的最后一个:
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
$userCnt = array_count_values($userArr);
ksort($userCnt);
$count = 0;
foreach ($userCnt as $key => $val) {
if($val >= $count) {
$result = $key;
$count = $val;
}
}
echo "$result appeared $count times";
$val
)是否大于或等于最后一个您的新评论似乎更简单。根据排序顺序对原稿进行排序并抓住第一个或最后一个:
rsort($userArr);
echo current($userArr);
//or
sort($userArr);
echo end($userArr);
如果因任何原因需要array_count_values()
:
$userCnt = array_count_values($userArr);
krsort($userCnt);
echo key($userCnt);