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

WBOY
Release: 2016-07-13 10:27:10
Original
1085 people have browsed it

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 ...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!