Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中的和数组_Php_Arrays_Sum - Fatal编程技术网

PHP中的和数组

PHP中的和数组,php,arrays,sum,Php,Arrays,Sum,我必须对一些数组求和(数组的数组)。我的阵列的结构如下所示: Array([id]=>some_id, [name]=>some_name, [value]=>float_value) 我知道我和以前一样有N个数组。我需要用相同的id求和 有什么想法吗 示例: ** **我不完全确定您想做什么-我假设您想要每个不同id的id的总和分组,但我可能错了 <?php //result array of sums $sums = array(); //example dat

我必须对一些数组求和(数组的数组)。我的阵列的结构如下所示:

Array([id]=>some_id, [name]=>some_name, [value]=>float_value)
我知道我和以前一样有N个数组。我需要用相同的id求和

有什么想法吗

示例:
**



**

我不完全确定您想做什么-我假设您想要每个不同id的id的总和分组,但我可能错了

<?php
//result array of sums
$sums = array();

//example data
$source = array(
    array('id'=>3, 'name'=>'some_name6', 'value'=>1.6),
    array('id'=>1, 'name'=>'some_name', 'value'=>1.4),
    array('id'=>1, 'name'=>'some_name2', 'value'=>7.2),
    array('id'=>2, 'name'=>'some_name3', 'value'=>4.4),
    array('id'=>1, 'name'=>'some_name4', 'value'=>1.2),
    array('id'=>2, 'name'=>'some_name5', 'value'=>1.4),
);

foreach ($source as $ar) {
    //create an entry for this id in the array of sums if does not exist.
    if (!isset($sums[ $ar['id'] ])) {
        $sums[ $ar['id'] ] = 0;
    }

    //add 'value' key to sum for that id
    $sums[ $ar['id'] ] += $ar['value'];
}

//sort by id
ksort($sums);

print_r($sums);

/* output:
Array
(
    [1] => 9.8
    [2] => 5.8
    [3] => 1.6
)
*/

这看起来像是来自数据库,查询是执行此类操作的最佳位置。(如果这不是来自数据库的数据,请忽略此答案)

PSEDOO代码:

$totals = array();

function add($in)
{
   global $totals;
   if(!isset($totals($in['id']))
   {
      $totals[$in['id']] = $in['value'];
   }else
   {
      $totals[$in['id']] += $in['value'];
   }
}

array_walk('add',$input_array);

var_dump($totals);

你认为是对的,但我只得到最后一个身份证的总和。我想我在某个地方搞错了。非常感谢
SELECT id, SUM(value)
FROM YourTable
-- add your WHERE-constraints here
GROUP BY id;
$totals = array();

function add($in)
{
   global $totals;
   if(!isset($totals($in['id']))
   {
      $totals[$in['id']] = $in['value'];
   }else
   {
      $totals[$in['id']] += $in['value'];
   }
}

array_walk('add',$input_array);

var_dump($totals);