php 基础问题二维数组求和 !

WBOY
Lepaskan: 2016-06-23 13:55:26
asal
1119 orang telah melayarinya

数组:
$a = array(array("a"=>"aa","a1"=>1,"a2"=>1),array("a"=>"bb","a1"=>2,"a2"=>2),array("a"=>"cc","a1"=>3,"a2"=>3),array("a"=>"aa","a1"=>1,"a2"=>1),array("a"=>"bb","a1"=>5,"a2"=>5))
第一个键值相同的元素 求和 
结果
$r = array(array("a"=>"aa","a1"=>2,"a2"=>2),array("a"=>"bb","a1"=>7,"a2"=>7),array("a"=>"cc","a1"=>3,"a2"=>3));


回复讨论(解决方案)

$a = array(  array("a" => "aa", "a1" => 1, "a2" => 1),  array("a" => "bb", "a1" => 2, "a2" => 2),  array("a" => "cc", "a1" => 3, "a2" => 3),  array("a" => "aa", "a1" => 1, "a2" => 1),  array("a" => "bb", "a1" => 5, "a2" => 5),);$res = array();foreach($a as $r) {  if(! isset($res[$r['a']])) $res[$r['a']] = $r;  else {    $res[$r['a']]['a1'] += $r['a1'];    $res[$r['a']]['a2'] += $r['a2'];  }}print_r(array_values($res));
Salin selepas log masuk
Array(    [0] => Array        (            [a] => aa            [a1] => 2            [a2] => 2        )    [1] => Array        (            [a] => bb            [a1] => 7            [a2] => 7        )    [2] => Array        (            [a] => cc            [a1] => 3            [a2] => 3        ))
Salin selepas log masuk

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan