The content of this article is to calculate the sum of a certain element in a two-dimensional array in PHP. Now I will share it with you. Friends in need can refer to it
<meta charset="utf-8"> <?php $ar = array( 2 => array( 'catid' => '6', 'cat' => 'dd', 'catdir' => '1522332388000',//2018-03-29 22:06:28 ), 6=> array( 'catid' => '5', 'cat' => 'dd', 'catdir' => '1522329351000'//2018-03-29 21:15:51 ), 7=> array( 'catid' => '4', 'cat' => 'ddfgd', 'catdir' => '1522328237000'//2018-03-29 20:56:15 ), 9=> array( 'catid' => '3', 'cat' => 'dd', 'catdir' => '1522327772000'//2018-03-29 20:49:32 ), 10=> array( 'catid' => '2', 'cat' => 'dvvd', 'catdir' => '1522325351000'//2018-03-29 20:09:11 ), 5 => array( 'catid' => '1', 'cat' => 'ddfgd', 'catdir' => '1522323606000',//2018-03-29 19:40:06 ), ); echo array_sum(array_map(create_function('$val', 'return $val["catid"];'), $ar)); ?>
Original example:
[0] => array(5) { ["id"] => string(2) "11" ["name"] => string(5) "1.jpg" ["suffix"] => string(3) "jpg" ["url"] => string(29) "./Uploads/1/5292f55d208e8.jpg" ["size"] => string(6) "715895" } [1] => array(5) { ["id"] => string(2) "12" ["name"] => string(22) "minisite数据库.docx" ["suffix"] => string(4) "docx" ["url"] => string(30) "./Uploads/1/5292f5606a52c.docx" ["size"] => string(5) "16667" }
I want to calculate the sum of sizes
(1)
echo
array_sum
(
array_map
(create_function(
'$val'
,
'return $val["size"];'
),
$arr
));
or
echo
array_sum
(
array_map
(
function
(
$val
){
return
$val
[
'size'
];},
$arr
));
(2)
$sum
= 0;
foreach
(
$arr
as
$item
){
$sum
+= (int)
$item
[
'size'
];
}
Quote: https://www.cnblogs.com/isykw/p/6217097.html
Related recommendations:
How to convert PHP two-dimensional array into one-dimensional array
How to remove duplicates from PHP two-dimensional array
The above is the detailed content of Calculate the sum of an element in a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!