php语言

php二维数组怎么求和

时间:2024-07-16 19:12:07 php语言 我要投稿
  • 相关推荐

php二维数组怎么求和

  导语:数组是php语言的一大难题。以下的是百分网小编为大家搜集的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

  )

  )

【php二维数组怎么求和】相关文章:

PHP判断数组是一维二维或几维实例09-10

php字符串与数组怎么转换10-04

C语言二维数组怎么写好10-27

c语言怎么定义一维数组和二维数组07-22

PHP数组函数知识10-24

简单PHP数组函数介绍09-26

php数组长度的方法10-05

PHP数组长度的技巧09-18

PHP数组的交集array-intersect()09-13

php递归遍历多维数组的方法10-06