将二维数组行按一列分组并对另一列求和
我有一个像这样的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让我们假设
$array
包含我们的数据。我们将遍历该数组并不断将time_spent
添加到另一个由url_id
键控的数组中。$ts_by_url
现在应包含:Let's pretend that
$array
contains our data. We will go through the array and continually add thetime_spent
to another array keyed byurl_id
.$ts_by_url
should now contain:OP发布了一个有趣的问题,但建议使用 array_count_values()< /a> 不适用;该函数不会对数组值求和,而是计算它们的频率。 @marcocassisa 的答案有效,但由于 E_NOTICES 的不幸发射而不够充分,尽管与任何数学问题无关。 (未定义的变量未设置,因此具有 NULL 值,但在数学上下文中,它将暂时强制为零值。)现代 PHP 通过在代码使用未定义变量时故意发出通知来阻止使用未定义变量,但从一个例外开始PHP 5.1:仅包含未定义变量的语句;请参阅此处。
为了纠正上述解决方案,可以使用两个 foreach 循环,一个用于设置索引键并初始化数组元素,而另一个则执行值的求和,如下所示:
请参阅 演示。
虽然令人满意,但该解决方案缺乏优雅性。尝试将两个 foreach 循环合并为一个,会对第二个元素产生负面影响,因为它被定义,然后不必要地重新定义。人们可以根据 @Charles 的答案进行编码,并创建 url id 编号索引(如果它尚不存在)。或者,您可以测试它是否已设置,如下所示:
参见 demo
注意:如果是数组element 被定义为 null,则 isset() 将返回 false,而 array_key_exists() 将返回 true。 Per,伊利亚·阿尔沙内茨基
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:
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:
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
为什么不更简单一点
Why not a simpler