gpt4 book ai didi

php - 数组php中的重复总和

转载 作者:行者123 更新时间:2023-12-04 16:03:37 24 4
gpt4 key购买 nike

我不确定在这方面要搜索什么功能,所以似乎无法帮助自己。看起来确实是一个明显的问题。我有一个数组,在有重复键的地方,我想添加值。例如:

这是我数组的一部分。

[1] => Array
(
[inputAvg] => 21.41 KB
[outputAvg] => 22.03 KB
[date] => 2011-08-01
)

[2] => Array
(
[inputAvg] => 182.63 KB
[outputAvg] => 186.05 KB
[date] => 2011-08-01
)

[3] => Array
(
[inputAvg] => 182.63 KB
[outputAvg] => 186.05 KB
[date] => 2011-08-02
)

[4] => Array
(
[inputAvg] => 4.84 MB
[outputAvg] => 4.93 MB
[date] => 2011-08-03
)

我想做的就是说数组的日期键在哪里相同(例如这里是 2011-08-01)我想显示一次这个日期,但是要显示重复项的组合值.... ?

例如

[1] => Array
(
[inputAvg] => 204.04 KB
[outputAvg] => 208.08 KB
[date] => 2011-08-01
)


[2] => Array
(
[inputAvg] => 182.63 KB
[outputAvg] => 186.05 KB
[date] => 2011-08-02
)

[3] => Array
(
[inputAvg] => 4.84 MB
[outputAvg] => 4.93 MB
[date] => 2011-08-03
)

最佳答案

<?php

$array = array(Array("inputAvg" => 21.41,"outputAvg" => 22.03,"date" => "2011-08-01"),
Array("inputAvg" => 182.63,"outputAvg" => 186.05,"date" => "2011-08-01" ),
Array("inputAvg" => 182.63, "outputAvg" => 186.05,"date" => "2011-08-02")
);

$res = array();
foreach($array as $vals){
if(array_key_exists($vals['date'],$res)){
$res[$vals['date']]['inputAvg'] += $vals['inputAvg'];
$res[$vals['date']]['outputAvg'] += $vals['outputAvg'];
$res[$vals['date']]['date'] = $vals['date'];
}
else{
$res[$vals['date']] = $vals;
}
}

echo "<pre>";
print_r($res);

?>

输出:

Array
(
[2011-08-01] => Array
(
[inputAvg] => 204.04
[outputAvg] => 208.08
[date] => 2011-08-01
)

[2011-08-02] => Array
(
[inputAvg] => 182.63
[outputAvg] => 186.05
[date] => 2011-08-02
)

)

关于php - 数组php中的重复总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14957901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com