首頁 > 後端開發 > php教程 > php 基础有关问题二维数组求和_PHP教程

php 基础有关问题二维数组求和_PHP教程

WBOY
發布: 2016-07-13 10:27:23
原創
969 人瀏覽過

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

  数组:

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

  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 基础问题二维数组求和 ! 数组: $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)) 第一个键...
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板