计算每个子数组中的项目以生成唯一键和计数的关联数组

发布于 2024-12-18 08:35:31 字数 470 浏览 3 评论 0原文

从下面的数组中可以看到,有 3 个元素出现在 11 月 18 日,另外两个元素出现在 11 月 22 日。有人能告诉我如何从该数组中分别检索 3 和 2 的计数吗?基本上,我想得到这样的结果:

2011 年 11 月 18 日 = 3 个项目

2011 年 11 月 22 日 = 2 个项目

当然,日期和不同日期的数量每次都会有所不同。这是数组:

[
    [
        ['2011-11-18 00:00:00' => 'C'],
        ['2011-11-18 00:00:00' => 'I'],
        ['2011-11-18 00:00:00' => 'S']
    ],
    [
        ['2011-11-22 00:00:00' => 'C'],
        ['2011-11-22 00:00:00' => 'S']
    ]
]

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:

Nov 18, 2011 = 3 items

Nov 22, 2011 = 2 items

Of course, the dates and the number of different dates will vary every time. Here is the array:

[
    [
        ['2011-11-18 00:00:00' => 'C'],
        ['2011-11-18 00:00:00' => 'I'],
        ['2011-11-18 00:00:00' => 'S']
    ],
    [
        ['2011-11-22 00:00:00' => 'C'],
        ['2011-11-22 00:00:00' => 'S']
    ]
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

如果没结果 2024-12-25 08:35:31

您可以使用:

count($array, COUNT_RECURSIVE);

计算嵌套数组树中的叶子数量

You can use:

count($array, COUNT_RECURSIVE);

Count number of leaves in nested array tree

愛上了 2024-12-25 08:35:31

这能满足您的需要吗?

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

打印:

Array ( [2011-11-18 00:00:00] => 3 [2011-11-22 00:00:00] => 2 )

注意:这假设您在构造数组时始终会获取数据,并且每个日期的格式都相同。如果您不能假设每个日期都会被格式化,那么这将是使用 date() 函数的简单转换。如果您不能假设您将获得与此完全相同的数据结构,那么解决该问题的最佳方法可能是通过递归函数。

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.

梦与时光遇 2024-12-25 08:35:31

发布的答案对于您的代表性示例来说是正确的,但我想添加另一个解决方案,无论您可能创建多少个嵌套数组,该解决方案都将起作用。它递归地迭代数组并计算所有子数组中的所有项目。

它返回数组中项目的总数。在第二个参数中,您可以指定一个数组
引用将包含(嵌套)数组中每个唯一键的计数。

示例:

<?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";

结果:

total count of items: 8
count per key: Array
(
    [a] => 3
    [b] => 3
    [c] => 1
    [e] => 1
)

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
)
北座城市 2024-12-25 08:35:31

假设您的数组示例具有代表性:

foreach ($array as $key => $value)
{
   echo count($value) . "<br />";
}

将回显每个主数组项中的数组数量。在您的示例中,这也是每个日期的条目数。

这当然不会检查日期本身

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

宁愿没拥抱 2024-12-25 08:35:31

对于您的特定 $array 结构,我认为最精简的方法是使用 foreach ,然后从每个中获取日期值和 count()值:

$dateCounts = array();
foreach($array as $date)
{
    $dateCounts[key($date[0])] = count($date);
}
var_dump($dateCounts);

使用您的 $array 给出:

array(2) {
  ["2011-11-18 00:00:00"]=> int(3)
  ["2011-11-22 00:00:00"]=> int(2)
}

如果您正在寻找更通用的方法,您可以使用 RecursiveArrayIteratorRecursiveIteratorIterator 来遍历所有叶子键/值元素,然后只计算键:

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$keyCounts = array();
foreach ($it as $key => $value)
{
    isset($keyCounts[$key]) ? $keyCounts[$key]++ : $keyCounts[$key] = 1; 
} 
var_dump($keyCounts);

希望这会有所帮助。

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:

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

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

淡莣 2024-12-25 08:35:31

您可以使用 array_walk_recursive()访问数组结构中的所有叶节点。

类似的东西应该适合你:

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

输出:

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
)

You can use array_walk_recursive() to get access to all of the leaf nodes in an array structure.

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
)
几度春秋 2024-12-25 08:35:31
<?php
$count0=count($array[0], COUNT_RECURSIVE)-count($array[0]);
$count1=count($array[1], COUNT_RECURSIVE)-count($array[1]);
<?php
$count0=count($array[0], COUNT_RECURSIVE)-count($array[0]);
$count1=count($array[1], COUNT_RECURSIVE)-count($array[1]);
居里长安 2024-12-25 08:35:31

这是我的递归变体:

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

这将返回:

Array ( [2011-11-18 00:00:00] => 3 [2011-11-22 00:00:00] => 3 )

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 )
半世晨晓 2024-12-25 08:35:31

给这只猫剥皮的方法有很多。我认为这取决于假设没有基准测试/性能要求的代码样式偏好。

所有这些脚本都会产生相同的结果。

  • 经典嵌套循环(演示

    $result = [];
    foreach($array 作为$set){
        foreach ($set as $row) {
            foreach ($row as $k => $_) {
                $结果[$k] = ($结果[$k] ?? 0) + 1;
            }
        }
    }
    var_export($结果);
    
  • key()count () 和一个经典循环(演示

    $result = [];
    foreach($array 作为$set){
        $结果[键($set[0])] = 计数($set); 
    }
    var_export($结果);
    
  • 使用 RecursiveIterator 的经典循环(演示

    $result = [];
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
    foreach ($it as $k => $_) {
        $结果[$k] = ($结果[$k] ?? 0) + 1; 
    }
    var_export($结果);
    
  • array_walk_recursive() (演示)

    $result = [];
    array_walk_recursive(
        $数组,
        函数 ($_, $k) use (&$result) {
            $结果[$k] = ($结果[$k] ?? 0) + 1;
        }
    );
    var_export($结果);
    
  • COUNT_RECURSIVE然后展平(演示

    var_export(
        数组合并(
            ...数组映射(
                fn($set) =>; [键($set[0]) =>计数($set, COUNT_RECURSIVE) - 计数($set)],
                $数组
            )
        )
    );
    
  • array_reduce() (演示)

    var_export(
        数组缩减(
            $数组,
            fn($结果, $设置) => $结果 + [键($set[0]) =>计数($集)],
            []
        )
    );
    

  • 展平、映射键,然后对值进行计数(演示

    var_export(
        数组计数值(
            数组映射(
                钥匙(...),
                数组合并(...$数组)
            )
        )
    );
    

So so many ways to skin this cat. I reckon it comes down to code styling preference assuming no benchmarking/performance requirements.

All of these scripts produce the same result.

  • Classic nested loops (Demo)

    $result = [];
    foreach ($array as $set) {
        foreach ($set as $row) {
            foreach ($row as $k => $_) {
                $result[$k] = ($result[$k] ?? 0) + 1;
            }
        }
    }
    var_export($result);
    
  • key() and count() with one classic loop (Demo)

    $result = [];
    foreach ($array as $set) {
        $result[key($set[0])] = count($set); 
    }
    var_export($result);
    
  • Classic loop with RecursiveIterator (Demo)

    $result = [];
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
    foreach ($it as $k => $_) {
        $result[$k] = ($result[$k] ?? 0) + 1; 
    }
    var_export($result);
    
  • array_walk_recursive() (Demo)

    $result = [];
    array_walk_recursive(
        $array,
        function ($_, $k) use (&$result) {
            $result[$k] = ($result[$k] ?? 0) + 1;
        }
    );
    var_export($result);
    
  • COUNT_RECURSIVE then flatten (Demo)

    var_export(
        array_merge(
            ...array_map(
                fn($set) => [key($set[0]) => count($set, COUNT_RECURSIVE) - count($set)],
                $array
            )
        )
    );
    
  • array_reduce() (Demo)

    var_export(
        array_reduce(
            $array,
            fn($result, $set) => $result + [key($set[0]) => count($set)],
            []
        )
    );
    
  • Flatten, map keys, then count values (Demo)

    var_export(
        array_count_values(
            array_map(
                key(...),
                array_merge(...$array)
            )
        )
    );
    
℡Ms空城旧梦 2024-12-25 08:35:31

如果你想计算一维和二维的项目,你可以尝试:

echo 'Size of unidimensional is: '.count($celda).'<br/>';

echo 'Size of bidimensional is: '.count($celda[0]).'<br/>';

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/>';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文