PHP计算多维数组中的项

时间:2021-05-18 21:31:28

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
                )

        )

)

9 个解决方案

#1


7  

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()函数的简单转换。如果您不能假设您将得到这样的数据结构,最好的解决方法可能是通过递归函数。

#2


20  

You can use:

您可以使用:

count($array, COUNT_RECURSIVE);

Count number of leaves in nested array tree

计算嵌套数组树中的叶数

#3


3  

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
)

#4


2  

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

这当然不会检查日期本身

#5


1  

You can use array_walk_recursive() to get access to all of 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
)

#6


1  

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(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和recursiveiterator来遍历所有叶键/值元素,然后只计算键数:

$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.

希望这个有帮助。

#7


0  

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 )

#8


0  

<?php
$count0=count($array[0], COUNT_RECURSIVE)-count($array[0]);
$count1=count($array[1], COUNT_RECURSIVE)-count($array[1]);

#9


0  

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/>';

#1


7  

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()函数的简单转换。如果您不能假设您将得到这样的数据结构,最好的解决方法可能是通过递归函数。

#2


20  

You can use:

您可以使用:

count($array, COUNT_RECURSIVE);

Count number of leaves in nested array tree

计算嵌套数组树中的叶数

#3


3  

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
)

#4


2  

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

这当然不会检查日期本身

#5


1  

You can use array_walk_recursive() to get access to all of 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
)

#6


1  

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(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和recursiveiterator来遍历所有叶键/值元素,然后只计算键数:

$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.

希望这个有帮助。

#7


0  

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 )

#8


0  

<?php
$count0=count($array[0], COUNT_RECURSIVE)-count($array[0]);
$count1=count($array[1], COUNT_RECURSIVE)-count($array[1]);

#9


0  

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/>';