Home > Backend Development > PHP Tutorial > PHP basics related issues: summation of two-dimensional arrays_PHP tutorial

PHP basics related issues: summation of two-dimensional arrays_PHP tutorial

WBOY
Release: 2016-07-13 10:27:23
Original
973 people have browsed it

PHP basic problem of summing two-dimensional arrays!

Array:

 $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))

Sum the first element with the same key value

Results

 $r = array(array("a"=>"aa","a1"=>2,"a2"=>2),array("a"=>"bb"," a1"=>7,"a2"=>7),array("a"=>"cc","a1"=>3,"a2"=>3));

 ------Solution--------------------

 $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));

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

 )

 )

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/820411.htmlTechArticlephp Basic problem of two-dimensional array summation! Array: $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)) The first key...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template