Home >Backend Development >PHP Tutorial >PHP二维数组如何求和?

PHP二维数组如何求和?

PHPz
PHPzOriginal
2016-06-02 11:31:375930browse

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

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

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

二维数组排序

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

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

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