php 多维数组键值求和,无循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16138395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:35:23  来源:igfitidea点击:

Sum values of multidimensional array by key without loop

phpmysqlarraysmultidimensional-array

提问by David

I have this:

我有这个:

Array (
    [0] => Array ( [f_count] => 1 [uid] => 105 ) 
    [1] => Array ( [f_count] => 0 [uid] => 106 ) 
    [2] => Array ( [f_count] => 2 [uid] => 107 ) 
    [3] => Array ( [f_count] => 0 [uid] => 108 ) 
    [4] => Array ( [f_count] => 1 [uid] => 109 ) 
    [5] => Array ( [f_count] => 0 [uid] => 110 ) 
    [6] => Array ( [f_count] => 3 [uid] => 111 )
)

What I need is: 7", which is the the sum of the f_countcolumn.

我需要的是:7“,这是f_count列的总和。

I've been trying to figure this out for a couple hours. I thought array_sum()would work, but not with a multidimensional array. So, I've tried figuring out how to isolate the f_counts by unset()or splicing or anything else, but every solution seems to involve a foreachloop. I've messed with array_map, array_walk, and others to no avail. I haven't found a function that works well with multidimensional arrays.

几个小时以来,我一直试图弄清楚这一点。我认为array_sum()会起作用,但不适用于多维数组。所以,我试图弄清楚如何f_count通过unset()或拼接或其他任何方式来隔离s ,但每个解决方案似乎都涉及一个foreach循环。我弄乱了array_map,,array_walk和其他人无济于事。我还没有找到适用于多维数组的函数。

I'm running PHP 5.4.

我正在运行 PHP 5.4。

Can someone please show me how to sum that column without a foreachloop?

有人可以告诉我如何在没有foreach循环的情况下对该列求和吗?

If it helps, the f_countvalues will never be higher than 100, and the uidvalues will always be greater than 100.

如果有帮助,f_count值将永远不会高于100,并且uid值将始终大于100



Alternatively, if there's a way to run my query differently such that the array is not multidimensional, that would obviously work as well.

或者,如果有一种方法可以以不同的方式运行我的查询,使得数组不是多维的,那显然也可以。

$query = "SELECT f_count, uid FROM users WHERE gid=:gid";
...
$array = $stmt->fetchAll();

I'm using PDO.

我正在使用 PDO。

回答by Anthony Harley

In php 5.5+ you can just used array_columnand array_sumlike so:

在PHP 5.5+你可以使用array_columnarray_sum像这样:

 $value = array_sum(array_column($arr,'f_count'));

回答by Ja?ck

You need to couple it with array_map()to select the f_countcolumn first:

您需要先将其与array_map()选择f_count列结合使用:

array_sum(array_map(function($item) { 
    return $item['f_count']; 
}, $arr));

Of course, internally, this performs a double loop; it's just that you don't see it inside the code. You could use array_reduce()to get rid of one loop:

当然,在内部,这会执行一个双循环;只是你没有在代码中看到它。你可以array_reduce()用来摆脱一个循环:

array_reduce($arr, function(&$res, $item) {
    return $res + $item['f_count'];
}, 0);

However, if speed is the only interest, foreachremains the fastest:

但是,如果速度是唯一的兴趣,则foreach仍然是最快的:

$sum = 0;
foreach ($arr as $item) {
    $sum += $item['f_count'];
}

This is thanks to the "locality" of the variables that you're using, i.e. there are no function calls used to calculate the final sum.

这要归功于您使用的变量的“局部性”,即没有用于计算最终总和的函数调用。

回答by Kodos Johnson

Alternatively, if there's a way to run my query differently such that the array is not multidimensional, that would obviously work as well.

$query = "SELECT f_count, uid FROM users WHERE gid=:gid"; 
... 
$array = $stmt->fetchAll(); 

I'm using PDO.

或者,如果有一种方法可以以不同的方式运行我的查询,使得数组不是多维的,那显然也可以。

$query = "SELECT f_count, uid FROM users WHERE gid=:gid"; 
... 
$array = $stmt->fetchAll(); 

我正在使用 PDO。

Yes, there is another way to run your query differently. You could use the aggregate function SUMto get the sum of all the f_countdirectly in your query. You would combine this with $stmt->fetchColumn()to get the value of the first column (which would be the sum) of the first row (which will be the only row since we used an aggregate function).

是的,还有另一种以不同方式运行查询的方法。您可以使用聚合函数直接在查询中SUM获取所有的总和f_count。您可以将其与$stmt->fetchColumn()第一行(这将是我们使用聚合函数后的唯一行)的第一列的值(这将是总和)结合起来。

Here is an example of how you could do this:

以下是如何执行此操作的示例:

$query = "SELECT SUM(f_count) FROM users WHERE gid=:gid";
$stmt = $pdo->prepare($query);
$stmt->execute(array(':gid' => 'yoursearchvalue'));
$sum = $stmt->fetchColumn();

回答by Raja Imran Qamer

for these type of situation foreach loop is the best possible option but if u have to do this for multiple times on a single page then u should put foreach loop in a function so that your code remain clean

对于这些类型的情况,foreach 循环是最好的选择,但是如果您必须在单个页面上多次执行此操作,那么您应该将 foreach 循环放在一个函数中,以便您的代码保持干净

function sum_index($arr, $col_name){
    $sum = 0;
    foreach ($arr as $item) {
        $sum += $item[$col_name];
    }
    return $sum;
}

Edit

编辑

After searching alot I found that array_columnfunction exist in php 5.5 + to get all values of single column as an array.

经过大量搜索后,我发现该array_column函数存在于 php 5.5 + 中,可以将单列的所有值作为数组获取。

For users having lower version You can use following function and call it with array sum if you want sum of all values as well.

对于较低版本的用户,如果您还想要所有值的总和,您可以使用以下函数并使用数组 sum 调用它。

//to get all values of single column from multidimensional array, this function exist in php 5.5 or greater.
if(!function_exists("array_column"))
{
    function array_column($array,$column_name)
    {
        return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
    }
}

If you want to get all values of single column then call above function like this:

如果要获取单列的所有值,请像这样调用上面的函数:

$newArray = array_column($array,$column_name);

If you want sum of all values of single column then use following code:

如果您想要单列的所有值的总和,请使用以下代码:

$newArraySum = array_sum(array_column($array,$column_name));

回答by kpk

Since you are using PHP 5.4 with PDO, there could be one more way to do it (available in PHP 5.1+):

由于您将 PHP 5.4 与 PDO 一起使用,因此可能还有另一种方法(在 PHP 5.1+ 中可用):

  • use the PDO fetchAll()function with the PDO::FETCH_COLUMNas the fetch_style, and the 0-indexed column number as the fetch_argument.
  • 使用 PDOfetchAll()函数PDO::FETCH_COLUMN作为fetch_style,将 0 索引的列号作为fetch_argument

As per your example, it could be:

根据您的示例,它可能是:

$query = "SELECT f_count, uid FROM users WHERE gid=:gid";
...
$array_fcount = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

Now use the array_sumfunction to sum the values of the array:

现在使用该array_sum函数对数组的值求和:

$fcount_sum = array_sum($array_fcount);

You could also consult the PHP documentation at http://php.net/manual/en/pdostatement.fetchall.php

您还可以在http://php.net/manual/en/pdostatement.fetchall.php查阅 PHP 文档

Hope this helps, and the performance could be better than looping! As already mentioned in other answers, in PHP 5.5 onwards you have the array_column()function to get $array_fcountdirectly from another array.

希望这会有所帮助,并且性能可能比循环更好!正如在其他答案中已经提到的,在 PHP 5.5 及更高版本中,您array_column()可以$array_fcount直接从另一个数组获取函数。