合并多个数组,然后按数组值计数排序

时间:2010-04-29 10:44:37

标签: php arrays sorting merge array-merge

请帮助我,我需要合并多个数组,然后按数组值计数对其进行排序。以下是问题:

$array1 = array("abc", "def", "ghi", "jkl", "mno");
$array2 = array("mno", "jkl", "mno", "ghi", "pqr", "stu");
$array3 = array_merge($array1, $array2);
$array4 = ???

print_r($array4);

我希望$array4的回报如下:

Array
(
[0] => mno
[1] => ghi
[2] => jkl
[3] => abc
[4] => def
[5] => pqr
[6] => stu
)

1 个答案:

答案 0 :(得分:11)

你可以这样做:

$array1 = array("abc", "def", "ghi", "jkl", "mno");
$array2 = array("mno", "jkl", "mno", "ghi", "pqr", "stu");
$array3 = array_merge($array1, $array2);

// get the array of count.
$array4 = array_count_values($array3);

// sort it in reverse order.
arsort($array4);

// extract just the keys.
$array4 = array_keys($array4);

Working example