PHP使用多维数组的PHP组

时间:2021-11-25 21:30:20

I have a php array like this:

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

 Array
    (
        [0] => Array
            (
                [url_id] => 2191238
                [time_spent] => 41

            )

        [1] => Array
            (
                [url_id] => 2191606
                [time_spent] => 215

            )
        [2] => Array
            (
                [url_id] => 2191606
                [time_spent] => 25

            )
    )

So, how to get the SUM of time_spent based on group by url_id (using array_count_values)

那么,如何通过url_id(使用array_count_values)获取基于group的time_spent的SUM

3 个解决方案

#1


1  

Why not a simpler

为什么不简单

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

#2


7  

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.

让我们假装$ 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 should now contain:

$ ts_by_url现在应该包含:

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

#3


0  

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.

OP发布了一个有趣的问题,但是使用array_count_values()的建议不适用;该函数不对数组值求和,但计算其频率。 @marcocassisa的答案有效但由于E_NOTICES的不幸排放而不足,尽管与任何数学问题无关。 (未定义的变量未设置,因此为NULL值,但在数学上下文中,它将暂时强制为零值。)现代PHP通过在代码使用时有意提出通知来阻止使用未定义的变量,只有一个例外PHP 5.1:仅包含未定义变量的语句;看这里。

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:

为了纠正上述解决方案,可以使用两个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"];
}

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:

虽然满意,但这种解决方案缺乏优雅。试图将两个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"]; 
}

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

注意:如果数组元素定义为null,则isset()将返回false,而array_key_exists()将返回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.

...如果您的应用程序不需要区分不存在的数组键和值恰好为NULL的数组键,则应使用isset(),因为它恰好要快一点。

#1


1  

Why not a simpler

为什么不简单

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

#2


7  

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.

让我们假装$ 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 should now contain:

$ ts_by_url现在应该包含:

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

#3


0  

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.

OP发布了一个有趣的问题,但是使用array_count_values()的建议不适用;该函数不对数组值求和,但计算其频率。 @marcocassisa的答案有效但由于E_NOTICES的不幸排放而不足,尽管与任何数学问题无关。 (未定义的变量未设置,因此为NULL值,但在数学上下文中,它将暂时强制为零值。)现代PHP通过在代码使用时有意提出通知来阻止使用未定义的变量,只有一个例外PHP 5.1:仅包含未定义变量的语句;看这里。

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:

为了纠正上述解决方案,可以使用两个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"];
}

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:

虽然满意,但这种解决方案缺乏优雅。试图将两个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"]; 
}

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

注意:如果数组元素定义为null,则isset()将返回false,而array_key_exists()将返回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.

...如果您的应用程序不需要区分不存在的数组键和值恰好为NULL的数组键,则应使用isset(),因为它恰好要快一点。