Merging multiple array then sorting by array value count
Asked Answered
D

1

6

Please help me, i need to merge multiple arrays then sorting it by array value count. Below is the problem:

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

print_r($array4);

I want the returns of $array4 like this:

Array
(
[0] => mno
[1] => ghi
[2] => jkl
[3] => abc
[4] => def
[5] => pqr
[6] => stu
)
Darra answered 29/4, 2010 at 10:44 Comment(0)
Z
11

You can do:

$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

Zoller answered 29/4, 2010 at 10:55 Comment(2)
by the way, is it possible to merge 3 or more arrays?Darra
@Sofyan: Yes, you can merge any number of arrays using array_merge php.net/manual/en/function.array-merge.phpZoller

© 2022 - 2024 — McMap. All rights reserved.