简体   繁体   English

如何计算PHP中多维数组中值的出现

[英]How to count occurrence of values in multidimensional array in php

First pardon me for the title as I couldn't find a proper title for it. 首先请原谅我的标题,因为我找不到合适的标题。 Please have a look at the array 请看一下数组

Array
(
[0] => Array
    (
        [0] => 2017
        [1] => Array
            (
                [0] => December
            )

    )

[1] => Array
    (
        [0] => 2017
        [1] => Array
            (
                [0] => December
            )

    )

[2] => Array
    (
        [0] => 2017
        [1] => Array
            (
                [0] => October
            )

    )

[3] => Array
    (
        [0] => 2016
        [1] => Array
            (
                [0] => December
            )

    )

 )

You can see 2017 is duplicated three times and inside 2017 December is duplicated two times. 您可以看到2017年重复了三次,而2017年12月内部重复了两次。 Now I want to get a multi dimensional array from this array that will show the occurrence of 2017 and it's month. 现在,我想从该数组中获取一个多维数组,该数组将显示2017年及其月份。

Something like 就像是

Array
(
  [2017] => 3
  [December]=> 2 // should be a nested array of 2017
  [October]=> 1 // should be a nested array of 2017
  [2016] => 1
  [December]=> 1 // should be a nested array of 2016
)

I tried array_count_values and some more custom code but all I managed to get 我尝试了array_count_values和更多的自定义代码,但是我设法得到了所有

Array
(
[2017] => 3
[2016] => 1
)

Edit: The months count doesn't has be keyed like this. 编辑:月数没有像这样键入。 All I need to know year occurrence and month occurrence under the year 我需要知道的年份和年份下的月份

Any help is highly appreciated. 非常感谢您的帮助。 Thanks. 谢谢。

You can try to loop then check if year key and month key already exist 您可以尝试循环,然后检查年密钥和月密钥是否已经存在

$group = [];
foreach ($array as $value) {
    $month = $value[1][0];
    if (!isset($group[$value[0]])) {
        $group[$value[0]] = array('count' => 0);
    }
    if (!isset($group[$value[0]][$month])) {
        $group[$value[0]][$month] = 0;
    }
    $group[$value[0]][$month] += 1;
    $group[$value[0]]['count'] += 1;
}

print_r($group);

If you don't necessarily need the count, you can change the first if condition 's execution to $group[$value[0]] = array(); 如果您不一定需要计数,则可以将if condition的执行方式更改为$group[$value[0]] = array(); and the line $group[$value[0]]['count'] += 1; $group[$value[0]]['count'] += 1;

foreach ($array as $value) {
    $month = $value[1][0];
    if (!isset($group[$value[0]])) {
        $group[$value[0]] = array();
    }
    if (!isset($group[$value[0]][$month])) {
        $group[$value[0]][$month] = 0;
    }
    $group[$value[0]][$month] += 1;
}

print_r($group);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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