Garry
Garry

Reputation: 454

counting items in an array

I have the array

Array ( [0] => Array ( [field_yourrating_rating] => 100 ) [1] => Array ( [field_yourrating_rating] => 80 ) [2] => Array ( [field_yourrating_rating] => 100 ) ) 

I want to be able to count the number of occurences of each value - for exmaple, 100 appears 1 time, and 80 appears one time.

I tried using array_count_values but it doesn't seem to work with a multidimensional array! What else can I try?

Upvotes: 1

Views: 200

Answers (2)

Michael
Michael

Reputation: 12836

If the array is only ever structured as it is in your example then this will work:

  foreach ($array as $value)
  {
    $count[current($value)] += 1;
  }

And then $count will be an array where the keys are the values of the input array and the values are the number of times they occur.

Upvotes: 1

Oliver M Grech
Oliver M Grech

Reputation: 3181

use the following function...

function array_searchRecursive($needle, $haystack, $strict = false, $path = array())
{
        if (!is_array($haystack))
        {
                return false;
        }
        foreach ($haystack as $key => $val)
        {
                if (is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path))
                {
                        $path = array_merge($path, array($key), $subPath);
                        return $path;
                } elseif ((!$strict && $val == $needle) || ($strict && $val === $needle))
                {
                        $path[] = $key;
                        return $path;
                }
        }
        return false;
}

and a simple

echo sizeof(array_searchRecursive(see arguments above));

would give you the answer ;)

have a nice day!

Upvotes: 0

Related Questions