Home  >  Article  >  Backend Development  >  Addition of two-dimensional arrays with identical key names in php_PHP tutorial

Addition of two-dimensional arrays with identical key names in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:27:101112browse

Addition of php two-dimensional arrays with the same key names

Array

 (

 [uid] => 19

 [pid] => Array

 (

 [0] => 91

 [1] => 81

 )

 [price] => Array

 (

 [0] => 6

 [1] => 14

 )

 [pnum] => Array

 (

 [0] => 1

 [1] => 1

 )

 )

Find the addition of values ​​with the same key name, such as (the addition result of price). The number of array items is uncertain

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

 $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

 )

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

You can also use foreach directly.

 $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 two-dimensional array with the same key name addition Array ( [uid] = 19 [pid] = Array ( [0 ] = 91 [1] = 81 ) [price] = Array ( [0] = 6 [1] = 14 ) [pnum] = Array ( [0] = 1 [1] = 1 ) ) Find values ​​with the same key name ...
Statement:
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