Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging multiple array then sorting by array value count

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
)
like image 964
Sofyan Sitorus Avatar asked Apr 29 '10 10:04

Sofyan Sitorus


People also ask

What is the time complexity of merging two sorted array is single sorted array using best algorithm?

The complexity is O(m log n). There are m iterations of the loop. Each insertion into a sorted array is an O(log n) operation.

How do I merge two unsorted arrays in sorted order?

Step 1 : Let arrayA and arrayB be the two unsorted integer arrays. Step 2 : Declare mergedArray with combined size of arrayA and arrayB . Step 3 : Initialize traversing indices for all three arrays to 0. Step 4 : Add all elements of arrayA to mergedArray .


1 Answers

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

like image 186
codaddict Avatar answered Sep 20 '22 00:09

codaddict