8

我已经搜索了很多这个问题。但是我在任何地方都找不到合适的解决方案。就像你array_count_values()为一维数组做一个一样,如果你想要类似类型的解决方案,你对多维数组做了什么?

例如-

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

我想要的输出是-

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

我该怎么做呢?

4

4 回答 4

15

使用数组的变量$arr,您可以这样做:

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

输出:

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

这是另一个将其生成为多维数组的版本:

$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;
        }
    }
}

输出:

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

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

)
于 2013-07-14T19:01:32.770 回答
2
<?php
  $array = array(array('07/11' => '134'), array('07/11' => '134'), array('07/12' => '145'));
  $count = array();
  foreach ($array as $val) {
    foreach ($val as $key => $subval) {
      $count[$key]++;
    }
  }
  print_r($count);
于 2013-07-14T18:56:37.090 回答
0

在你的位置,我会改变数据数组的结构。在你的情况下:

Array( 
    [07/11] => Array
        (
            [0] => 134,
            [1] => 134,
            [2] => 145,
            [3] => 145,
            ...
        )
)
于 2013-07-14T18:58:00.037 回答
0

聪明的方法,我们知道array_count_values():计算数组的所有值

就像您对一维数组执行 array_count_values() 一样,您对多维数组执行什么操作。

我们通过将其转换为一维数组来做到这一点,然后我们调用我们的函数

$input = array(
    array('07/11' => '134'),
    array('07/11' => '134'), 
    array('07/11' => '145'),
    array('07/11' => '145'),
    array('07/12' => '134'), 
    array('07/12' => '99')
    );
$output = [];
foreach ($input as $inner){
    foreach ($inner as $key => $value){
        $output[] = "Date: $key, ID: $value, Count:";
    }
}

输出:如你所料

foreach(array_count_values($output) as $key => $value) {
    echo "$key $value<br>";
}

/*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*/
于 2021-05-09T21:13:31.330 回答