Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...