Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

php - array_count_values of a multi dimensional array?

I have searched this question a lot. But I could not find a proper solution anywhere. Just like you do an array_count_values() for a single dimensional array, what do you do for a multi dimensional array if you want similar type of a solution?

For example-

Array
(
    [0] => Array
        (
            [07/11] => 134
        )

    [1] => Array
        (
            [07/11] => 134
        )

    [2] => Array
        (
            [07/11] => 145
        )

    [3] => Array
        (
            [07/11] => 145
        )

    [4] => Array
        (
            [07/12] => 134
        )

    [5] => Array
        (
            [07/12] => 99
        )
)

The output that I want is-

Date: 07/11, ID: 134, Count: 2
Date: 07/11, ID: 145, Count: 2
Date: 07/12, ID: 135, Count: 1
Date: 07/12, ID: 99, Count: 1

How do I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using the variable $arr for your array, you could do this:

$out = array();
foreach ($arr as $key => $value){
    foreach ($value as $key2 => $value2){
        $index = $key2.'-'.$value2;
        if (array_key_exists($index, $out)){
            $out[$index]++;
        } else {
            $out[$index] = 1;
        }
    }
}
var_dump($out);

Output:

Array
(
    [07/11-134] => 2
    [07/11-145] => 2
    [07/12-134] => 1
    [07/12-99] => 1
)

Here's another version that produces it as a multidimensional array:

$out = array();
foreach ($arr as $key => $value){
    foreach ($value as $key2 => $value2){
        if (array_key_exists($key2, $out) && array_key_exists($value2, $out[$key2])){
            $out[$key2][$value2]++;
        } else {
            $out[$key2][$value2] = 1;
        }
    }
}

Output:

Array
(
    [07/11] => Array
        (
            [134] => 2
            [145] => 2
        )

    [07/12] => Array
        (
            [134] => 1
            [99] => 1
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...