![](/img/trans.png)
[英]How to count elements in multidimensional array in php by their occurrence and quantity value
[英]How to count occurrence of values in multidimensional array in php
首先请原谅我的标题,因为我找不到合适的标题。 请看一下数组
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
)
)
)
您可以看到2017年重复了三次,而2017年12月内部重复了两次。 现在,我想从该数组中获取一个多维数组,该数组将显示2017年及其月份。
就像是
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
)
我尝试了array_count_values
和更多的自定义代码,但是我设法得到了所有
Array
(
[2017] => 3
[2016] => 1
)
编辑:月数没有像这样键入。 我需要知道的年份和年份下的月份
非常感谢您的帮助。 谢谢。
您可以尝试循环,然后检查年密钥和月密钥是否已经存在
$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 condition
的执行方式更改为$group[$value[0]] = array();
和$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.