php PHP计算多维数组中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8284302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP count items in a multi-dimensional array
提问by DanielAttard
As you can see from the following array, there are three elements that appear on Nov 18, and another two elements that appear on Nov 22. Can someone tell me how I can retrieve the counts of 3 and 2 respectively from this array? Basically, I want to end up with a result something like this:
从下面的数组中可以看出,11 月 18 日出现了三个元素,11 月 22 日出现了另外两个元素。有人能告诉我如何从这个数组中分别检索 3 和 2 的计数吗?基本上,我想最终得到这样的结果:
Nov 18, 2011 = 3 items
2011 年 11 月 18 日 = 3 个项目
Nov 22, 2011 = 2 items
2011 年 11 月 22 日 = 2 个项目
Of course, the dates and the number of different dates will vary every time. Here is the array:
当然,日期和不同日期的数量每次都会有所不同。这是数组:
Array
(
[0] => Array
(
[0] => Array
(
[2011-11-18 00:00:00] => C
)
[1] => Array
(
[2011-11-18 00:00:00] => I
)
[2] => Array
(
[2011-11-18 00:00:00] => S
)
)
[1] => Array
(
[0] => Array
(
[2011-11-22 00:00:00] => C
)
[1] => Array
(
[2011-11-22 00:00:00] => S
)
)
)
采纳答案by Godwin
Does this work for what you need?
这是否适合您的需要?
$dates = array(array(array("2011-11-18 00:00:00" => C), array("2011-11-18 00:00:00" => I),array
("2011-11-18 00:00:00" => S)),
array(array("2011-11-22 00:00:00" => C), array("2011-11-22 00:00:00" => S)));
$date_count = array(); // create an empty array
foreach($dates as $date) { // go thought the first level
foreach($date as $d) { // go through the second level
$key = array_keys($d); // get our date
// here we increment the value at this date
// php will see it as 0 if it has not yet been initialized
$date_count[$key[0]]++;
}
}
// show what we have
print_r($date_count);
Prints:
印刷:
Array ( [2011-11-18 00:00:00] => 3 [2011-11-22 00:00:00] => 2 )
Note: this assumes that you will always be getting data as you structured your array and that each date will be formatted the same. If you can't assume each date will be formatted, this would be a simple conversion using the date() function. If you can't assume that you will get data structured exactly like this, the best way to tackle that would probably be through a recursive function.
注意:这假设您在构建数组时始终会获取数据,并且每个日期的格式都相同。如果您不能假设每个日期都将被格式化,这将是使用 date() 函数的简单转换。如果您不能假设您将获得完全像这样结构化的数据,那么解决这个问题的最佳方法可能是通过递归函数。
回答by emilie zawadzki
回答by Kaii
the posted answers are correct for your representative example, but i would like to add another solution, that will work regardless how many nested arrays you may create. it iterates the array recursively and counts all items in all sub-arrays.
发布的答案对于您的代表性示例是正确的,但我想添加另一个解决方案,无论您可能创建多少个嵌套数组,该解决方案都将起作用。它递归地迭代数组并计算所有子数组中的所有项目。
it returns the total count of items in the array. in the second argument you can specify an array reference which will contain the count per unique key in the (nested) array(s).
它返回数组中项目的总数。在第二个参数中,您可以指定一个数组引用,该引用将包含(嵌套)数组中每个唯一键的计数。
example:
例子:
<?php
$deeply_nested = array(
'a' => 'x',
'b' => 'x',
'c' => 'x',
'd' => array(
'a' => 'x',
'b' => 'x',
'c' => array(
'a' => 'x',
'b' => 'x'
),
'e' => 'x'
)
);
function count_nested_array_keys(array &$a, array &$res=array()) {
$i = 0;
foreach ($a as $key=>$value) {
if (is_array($value)) {
$i += count_nested_array_keys($value, &$res);
}
else {
if (!isset($res[$key]) $res[$key] = 0;
$res[$key]++;
$i++;
}
}
return $i;
}
$total_item_count = count_nested_array_keys($deeply_nested, $count_per_key);
echo "total count of items: ", $total_item_count, "\n";
echo "count per key: ", print_r($count_per_key, 1), "\n";
results in:
结果是:
total count of items: 8
count per key: Array
(
[a] => 3
[b] => 3
[c] => 1
[e] => 1
)
回答by Sylverdrag
Assuming that your array example is representative:
假设您的数组示例具有代表性:
foreach ($array as $key => $value)
{
echo count($value) . "<br />";
}
Will echo the number of arrays within each of the main array items. In your example, that would also be the number of entries for each date.
将回显每个主数组项中的数组数。在您的示例中,这也是每个日期的条目数。
This does not of course check the dates themselves
这当然不会检查日期本身
回答by hafichuk
You can use array_walk_recursive()
to get access to allof the leaf nodes in an array structure.
您可以使用array_walk_recursive()
来访问数组结构中的所有叶节点。
Something akin to this should work for you:
类似的东西应该适合你:
<?php
$data = array(
array(
array('2011-11-18 00:00:00' => 'C'),
array('2011-11-18 00:00:00' => 'I'),
array('2011-11-18 00:00:00' => 'S')),
array(
array('2011-11-22 00:00:00' => 'C'),
array('2011-11-22 00:00:00' => 'S')));
function countleafkeys($value, $key, $userData)
{
echo "$key\n";
if(!isset($userData[$key])) {
$userData[$key] = 1;
} else {
$userData[$key]++;
}
}
$result = array();
array_walk_recursive($data, 'countleafkeys', &$result);
print_r($result);
Outputs:
输出:
2011-11-18 00:00:00
2011-11-18 00:00:00
2011-11-18 00:00:00
2011-11-22 00:00:00
2011-11-22 00:00:00
Array
(
[2011-11-18 00:00:00] => 3
[2011-11-22 00:00:00] => 2
)
回答by hakre
For your specific $array
structure I think the most lean way is using foreach
and then getting the date value and the count()
out of each value:
对于您的特定$array
结构,我认为最精简的方法是使用foreach
然后获取日期值和count()
每个值:
$dateCounts = array();
foreach($array as $date)
{
$dateCounts[key($date[0])] = count($date);
}
var_dump($dateCounts);
With your $array
this gives:
有了你$array
这给:
array(2) {
["2011-11-18 00:00:00"]=> int(3)
["2011-11-22 00:00:00"]=> int(2)
}
If you're looking for a more general way, you can make use of RecursiveArrayIterator
and RecursiveIteratorIterator
to traverse over all leaf key/value elements and then just count the keys:
如果您正在寻找更通用的方法,您可以使用RecursiveArrayIterator
并RecursiveIteratorIterator
遍历所有叶键/值元素,然后只计算键:
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$keyCounts = array();
foreach ($it as $key => $value)
{
isset($keyCounts[$key]) ? $keyCounts[$key]++ : $keyCounts[$key] = 1;
}
var_dump($keyCounts);
Hope this helps.
希望这可以帮助。
回答by mintobit
Here is my recursive variant:
这是我的递归变体:
$arr = array(
'0' => array(
'0' => array('2011-11-18 00:00:00' => 'C'),
'1' => array('2011-11-18 00:00:00' => 'I'),
'2' => array('2011-11-18 00:00:00' => 'S')
),
'1' => array(
'0' => array('2011-11-22 00:00:00' => 'C'),
'1' => array('2011-11-22 00:00:00' => 'S')
),
'2' => array(
'0' => array(
'0' => array('2011-11-22 00:00:00' => 'D')
)
)
);
function count_values($array, &$result = array(), $counter = 0)
{
foreach ($array as $key => $data)
{
if (is_array($data))
{
count_values($data, $result, $counter);
}
else
{
array_key_exists($key, $result) ? $result[$key]++ : $result[$key] = 1;
}
}
return $result;
}
print_r(count_values($arr));
This will return:
这将返回:
Array ( [2011-11-18 00:00:00] => 3 [2011-11-22 00:00:00] => 3 )
回答by itsazzad
<?php
$count0=count($array[0], COUNT_RECURSIVE)-count($array[0]);
$count1=count($array[1], COUNT_RECURSIVE)-count($array[1]);
回答by Ismael Fdez
If you want count the items unidimensional and bidimensional you can try:
如果你想计算一维和二维的项目,你可以尝试:
echo 'Size of unidimensional is: '.count($celda).'<br/>';
echo 'Size of bidimensional is: '.count($celda[0]).'<br/>';