欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php二维数组雷同键名相加_PHP教程

程序员文章站 2022-04-21 21:32:21
...
  php二维数组相同键名相加

  Array

  (

  [uid] => 19

  [pid] => Array

  (

  [0] => 91

  [1] => 81

  )

  [price] => Array

  (

  [0] => 6

  [1] => 14

  )

  [pnum] => Array

  (

  [0] => 1

  [1] => 1

  )

  )

  求相同键名的值相加如(price 的相加结果) 数组条数不确定

  ------解决方案--------------------

  $ar = Array(

  'uid' => 19,

  'pid' => Array (

  0 => 91,

  1 => 81,

  ),

  'price' => Array (

  0 => 6,

  1 => 14,

  ),

  'pnum' => Array (

  0 => 1,

  1 => 1,

  ),

  );

  $r = array_map(function($t) {

  return is_array($t) ? array_sum($t) : $t;

  }, $ar);

  print_r($r);

  Array

  (

  [uid] => 19

  [pid] => 172

  [price] => 20

  [pnum] => 2

  )

  ------解决方案--------------------

  直接用foreach也可以。

  $ar = Array(

  'uid' => 19,

  'pid' => Array (

  0 => 91,

  1 => 81,

  ),

  'price' => Array (

  0 => 6,

  1 => 14,

  ),

  'pnum' => Array (

  0 => 1,

  1 => 1,

  ),

  );

  foreach($ar as $k=>$v){

  $arr[$k] = is_array($v) ? array_sum($v) : $v;

  }

  print_r($arr);

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/820418.htmlTechArticlephp二维数组相同键名相加 Array ( [uid] = 19 [pid] = Array ( [0] = 91 [1] = 81 ) [price] = Array ( [0] = 6 [1] = 14 ) [pnum] = Array ( [0] = 1 [1] = 1 ) ) 求相同键名的值...