1

If I have an array with the following structure, I need to determine which Description is used the most.

So, in this case, you can see that Feline is used in the first and 4th grouping, so Description->Feline would be the answer as it is used the most. How can I script it in PHP to output that answer?

So, if I have an array below called $stuff:

 Array (

 [1] => Array (
        [Title] => Cat
        [Description] => Feline
        [Age] => 7

        ) 

 [2] => Array (
        [Title] => Dog
        [Description] => Canine
        [Age] => 8

        )

 [3] =>
       Array (
        [Title] => Birdie
        [Description] => Winged Beast of the Air
        [Age] => Eternal
       )

 [4] =>  
       (     
        [Title] => Kitten
        [Description] => Feline
        [Age] => 1
       )

 )

I found this code:

 $c = array_count_values($stuff); 
 $val = array_search(max($c), $c);

But that won't work, because I need to count only the Description field, not all of the fields. So, how do I go in and narrow it down or tighten it up so that I only count and get the number of matching descriptions there are.

My thought was to try:

 $c = array_count_values($stuff['Description']); 
 $val = array_search(max($c), $c);

But that didn't work. Am I missing something else?

CRAIG
  • 977
  • 2
  • 11
  • 25

1 Answers1

1

Please check this below:-

<?php
$stuff =  Array (
 '1' => Array (
        'Title' => 'Cat',
        'Description' => 'Feline',
        'Age' => 7

        ),
    '2' => Array (
        'Title' => 'Dog',
        'Description' => 'Caine',
        'Age' => 8

        ),
    '3' => Array (
        'Title' => 'Birdie',
        'Description' => 'Winged Beast of the Air',
        'Age' => 'Eternal'

        ),
 '4' => Array (     
        'Title' => 'Kitten',
        'Description' => 'Feline',
        'Age' => 1,
       )

 );


$description_count = array();
foreach ($stuff as $key=>$value) {
  // check and add to the description_count array
  if (isset($description_count[$value['Description']])) {
    $description_count[$value['Description']]++;
  }
  // if not exist then initialize 1
  else $description_count[$value['Description']] = 1;

 //in single line you can do it 
  $description_count[$value['Description']] = isset($description_count[$value['Description']]) ? $description_count[$value['Description']]++ : 1;
}
echo "<pre/>";print_r($description_count);

Output:- https://eval.in/388305

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98