将二维数组行按一列分组并对另一列求和

发布于 2024-10-21 23:27:47 字数 332 浏览 2 评论 0原文

我有一个像这样的 php 数组:

[
    ['url_id' => 2191238, 'time_spent' => 41],
    ['url_id' => 2191606, 'time_spent' => 215],
    ['url_id' => 2191606, 'time_spent' => 25]
]

How to get the SUM of time_spent based on group by url_id (using array_count_values?)?

I have a php array like this:

[
    ['url_id' => 2191238, 'time_spent' => 41],
    ['url_id' => 2191606, 'time_spent' => 215],
    ['url_id' => 2191606, 'time_spent' => 25]
]

How to get the SUM of time_spent based on group by url_id (using array_count_values?)?

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

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

发布评论

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

评论(3

可爱咩 2024-10-28 23:27:47

让我们假设 $array 包含我们的数据。我们将遍历该数组并不断将 time_spent 添加到另一个由 url_id 键控的数组中。

$ts_by_url = array();
foreach($array as $data) {
    if(!array_key_exists($data['url_id'], $ts_by_url))
        $ts_by_url[ $data['url_id'] ] = 0;
    $ts_by_url[ $data['url_id'] ] += $data['time_spent'];
}

$ts_by_url 现在应包含:

2191238 => 41
2191606 => 240 // == 215 + 25

Let's pretend that $array contains our data. We will go through the array and continually add the time_spent to another array keyed by url_id.

$ts_by_url = array();
foreach($array as $data) {
    if(!array_key_exists($data['url_id'], $ts_by_url))
        $ts_by_url[ $data['url_id'] ] = 0;
    $ts_by_url[ $data['url_id'] ] += $data['time_spent'];
}

$ts_by_url should now contain:

2191238 => 41
2191606 => 240 // == 215 + 25
怪我入戏太深 2024-10-28 23:27:47

OP发布了一个有趣的问题,但建议使用 array_count_values()< /a> 不适用;该函数不会对数组值求和,而是计算它们的频率。 @marcocassisa 的答案有效,但由于 E_NOTICES 的不幸发射而不够充分,尽管与任何数学问题无关。 (未定义的变量未设置,因此具有 NULL 值,但在数学上下文中,它将暂时强制为零值。)现代 PHP 通过在代码使用未定义变量时故意发出通知来阻止使用未定义变量,但从一个例外开始PHP 5.1:仅包含未定义变量的语句;请参阅此处

为了纠正上述解决方案,可以使用两个 foreach 循环,一个用于设置索引键并初始化数组元素,而另一个则执行值的求和,如下所示:

<?php

// set keys and initialize
foreach($arr as $data) {
    $its_by_url[ $data["url_id"] ] = 0;
} 

// now can sum values by url id number:
foreach($arr as $data) {
    $its_by_url[ $data["url_id"] ] += $data["time_spent"];
}

请参阅 演示

虽然令人满意,但该解决方案缺乏优雅性。尝试将两个 foreach 循环合并为一个,会对第二个元素产生负面影响,因为它被定义,然后不必要地重新定义。人们可以根据 @Charles 的答案进行编码,并创建 url id 编号索引(如果它尚不存在)。或者,您可以测试它是否已设置,如下所示:

<?php
foreach($arr as $data) {
   if ( !isset( $its_by_url[ $data["url_id"] ] ) ) {
             $its_by_url[ $data["url_id"] ] = 0;
   }
   $its_by_url[ $data["url_id"] ] += $data["time_spent"]; 
}

参见 demo

注意:如果是数组element 被定义为 null,则 isset() 将返回 false,而 array_key_exists() 将返回 true。 Per,伊利亚·阿尔沙内茨基

...如果您的应用程序不需要区分
数组键不存在且其值恰好为
NULL 你应该使用 isset() 因为它恰好有点
更快。

The OP posted an interesting problem, but the suggestion of using array_count_values() was not applicable; the function does not sum array values but counts their frequency. The answer of @marcocassisa works but is insufficient because of the unfortunate emission of E_NOTICES, albeit unrelated to any math issue. (An undefined variable is unset and thus of NULL value, but in a math context it will temporarily be coerced into a value of zero.) Modern PHP discourages the use of undefined variables by intentionally raising notices when code utilizes them, with one exception starting with PHP 5.1: a statement consisting of only an undefined variable; see here.

To rectify the aforementioned solution, one might use two foreach loops, one to set the index keys and initialize the array elements while the other would perform the summing of values, as follows:

<?php

// set keys and initialize
foreach($arr as $data) {
    $its_by_url[ $data["url_id"] ] = 0;
} 

// now can sum values by url id number:
foreach($arr as $data) {
    $its_by_url[ $data["url_id"] ] += $data["time_spent"];
}

see demo.

While satisfactory, this solution lacks elegance. Attempting to combine the two foreach loops into one, will negatively impact the second element, as it gets defined and then needlessly redefined. One could code per the answer of @Charles and create the url id numbered index if it doesn't already exist. Or, you could test to see if it is set, as follows:

<?php
foreach($arr as $data) {
   if ( !isset( $its_by_url[ $data["url_id"] ] ) ) {
             $its_by_url[ $data["url_id"] ] = 0;
   }
   $its_by_url[ $data["url_id"] ] += $data["time_spent"]; 
}

see demo

Note: if an array element were defined as null, then isset() would return false while array_key_exists() would return true. Per, Ilia Alshanetsky

... if your application does not need to distinguish between an
array key that does not exist and one whose value happens to be
NULL you should use isset() because it happens to be a little
faster.

不一样的天空 2024-10-28 23:27:47

为什么不更简单一点

$ts_by_url = array();
foreach($array as $data) {
    $ts_by_url[ $data['url_id'] ] += $data['time_spent'];
}

Why not a simpler

$ts_by_url = array();
foreach($array as $data) {
    $ts_by_url[ $data['url_id'] ] += $data['time_spent'];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文