-4

I want to sort the array in order to find the most common word placed in it here is the array:-

Array ( [0] => Array ( [0] => this [1] => burger [2] => is [3] => owsum ) [1] 
=> Array ( [0] => this [1] => burger [2] => is [3] => owsum ) [2] => Array ( 
[0] => love [1] => this [2] => burger ) [3] => Array ( [0] => love [1] => this 
[2] => burger ) [4] => Array ( [0] => kamaaal [1] => burger ) [5] => Array ( 
[0] => kamaaal [1] => burger ) [6] => Array ( [0] => this [1] => burger [2] => 
is [3] => owsum ) )
Muhammad Hassan
  • 61
  • 1
  • 1
  • 7
  • If you are trying to get element that are repeated the most use try finding the duplicate elements in the array. [see this](https://stackoverflow.com/questions/13633954/how-do-i-count-occurrence-of-duplicate-items-in-array) . but I think you should have a proper array first. – Regolith Jul 15 '17 at 10:38
  • 1
    First flatten the array (`iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($input)),false)`) then use [`array_count_values`](http://php.net/array-count-values) – Niet the Dark Absol Jul 15 '17 at 10:39

2 Answers2

0
$max= array();
foreach ($arr as $key => $value){
    foreach ($value as $key2 => $value2){
        $index = $value2;
        if (array_key_exists($index, $max)){
            $max[$index]++;
        } else {
            $max[$index] = 1;
        }
    }
}
echo array_search(max($max),$max);
Osama
  • 2,912
  • 1
  • 12
  • 15
0
$a = Array (
    '0' => Array ( '0' => 'this', '1' => 'burger', '2' => 'is', '3' => 'owsum', ) ,
    '1' => Array ( '0' => 'this', '1' => 'burger', '2' => 'is', '3' => 'owsum', ) ,
    '2' => Array ( '0' => 'love', '1' => 'this',  '2' => 'burger', ) ,
    '3' => Array ( '0' => 'love', '1' => 'this',  '2' => 'burger', ) ,
    '4' => Array ( '0' => 'kamaaal', '1' => 'burger', ) ,
    '5' => Array ( '0' => 'kamaaal', '1' => 'burger', ) ,
    '6' => Array ( '0' => 'this', '1' => 'burger', '2' => 'is', '3' => 'owsum', ) ,
);
// Merge all subarrays into one
$merged = call_user_func_array('array_merge', $a);

// Apply `array_count_values` to count number of occurencies
$count_values = array_count_values($merged);

// Sort this array preserving keys
arsort($count_values);

// Do whatever you want - iterate with foreach, get first element etc.
u_mulder
  • 54,101
  • 5
  • 48
  • 64