PHP二维数组如何求和?

PHPz
Release: 2020-09-04 15:43:07
Original
5849 people have browsed it

PHP二维数组如何求和?

PHP二维数组求和的方法:

1、使用array_sum和array_map函数求和

1)、PHP7.2以下可用

<?php
$arr = array(
0=>array(&#39;id&#39;=>1,&#39;tol&#39;=>10),
1=>array(&#39;id&#39;=>3,&#39;tol&#39;=>12),
2=>array(&#39;id&#39;=>8,&#39;tol&#39;=>5)
);
//输出tol值的和
echo array_sum(array_map(create_function(&#39;$val&#39;, &#39;return $val["tol"];&#39;), $arr));
?>
Copy after login

2)、PHP7.2及以上可用(因为php7.2废弃create_function)

<?php
$arr = array(
0=>array(&#39;id&#39;=>1,&#39;tol&#39;=>10),
1=>array(&#39;id&#39;=>3,&#39;tol&#39;=>12),
2=>array(&#39;id&#39;=>8,&#39;tol&#39;=>5)
);

//输出
echo array_sum(array_map(function($val){return $val[&#39;tol&#39;];}, $arr));
?>
Copy after login

2、通用foreach循环

<?php
$arr = array(
0=>array(&#39;id&#39;=>1,&#39;tol&#39;=>10),
1=>array(&#39;id&#39;=>3,&#39;tol&#39;=>12),
2=>array(&#39;id&#39;=>8,&#39;tol&#39;=>5)
);

$sum = 0;

//foreach循环
foreach($arr as $item){
$sum += (int) $item[&#39;tol&#39;];
}

//输出
echo $sum;
?>
Copy after login

二维数组排序

//根据字段last_name对数组$data进行降序排列
$last_names=array_column($data,&#39;last_name&#39;);
array_multisort($last_names,SORT_DESC,$data);
Copy after login

更多相关知识,请访问 PHP中文网!!

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!