user1320990
user1320990

Reputation:

Count number of certain value in multidimensional array

How can I count the number of a certain value from a multidimensional array? For example:

array(
    array ('stack' => '1')
    array ('stack' => '1')
    array ('stack' => '1')
    array ('stack' => '1')
    array ('stack' => '2')
    array ('stack' => '2')
)

In this example the result should be:

stack == 1 => 4 matches
stack == 2 => 2 matches

Upvotes: 1

Views: 3702

Answers (5)

Hardik
Hardik

Reputation: 1411

You required some modification but this will helpful to you

<?php


    function array_count_values_of($value, $array) {
        $counts = array_count_values($array);
        return $counts[$value];
    }

    $array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);
    $array2 = array_unique($array);
    for($i=0 ; $i<count($array2) ; $i++)
    {
        $temp = array_count_values_of($array2[$i], $array);
        $result[$i][0] = $array2[$i];
        $result[$i][1] = $temp;
    }

    print_r($result);

    ?>

Upvotes: 1

lynks
lynks

Reputation: 5689

As Ray says, given your data structure, your only option is to traverse the whole array and count up as you go along.

If you are worried about performance, you might want to consider using a different data structure (perhaps alongside the array). The second data structure would be something like a hash that takes the array values as keys and contains an ongoing count that you could build while you are building the array.

That way you take a minimal performance hit, rather than having to reiterate all over again.

Upvotes: 1

Fabien
Fabien

Reputation: 13406

$occur = array();

foreach ($array as $item) {
    foreach ($item as $k => $v) {
        $occur["$k == $v"]++;
    }
}

Upvotes: 1

nickb
nickb

Reputation: 59699

You'd have to loop it yourself:

$counts = array();
foreach( $array as $value) {
    foreach( $value as $k => $v) {
        if( !isset( $counts[$k])) $counts[$k] = array();
        if( !isset( $counts[$k][$v])) $counts[$k][$v] = 0;
        $counts[$k][$v] += 1;
    }
}

foreach( $counts as $k => $v1)
    foreach( $v1 as $v => $count)
        echo "$k == $v => $count matches\n";

This will print:

stack == 1 => 4 matches
stack == 2 => 2 matches

Upvotes: 1

Ray
Ray

Reputation: 41428

I'd just simply loop through it and push the results to a new result array (but I'm not going to code it for you).

You can do more complex things like use array_walk/array_filter with a callback function to process it... but that might be less efficient.

see this post: PHP Multidimensional Array Count

Upvotes: 0

Related Questions