简体   繁体   中英

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

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
$occur = array();

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

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.

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);

    ?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM