萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php二維數組雷同鍵名相加

php二維數組雷同鍵名相加

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

copyright © 萬盛學電腦網 all rights reserved