How to sum a column of a multidimensional array in php

青灯夜游
Release: 2023-03-16 06:08:01
Original
3111 people have browsed it

Sum method: 1. Use array_column() to obtain all elements of a specified column in a multi-dimensional array. The syntax "rray_column(array, 'specified column name')" will return a result array containing all elements; 2. Use "array_sum (result array)" to calculate the sum of all elements in the result array.

How to sum a column of a multidimensional array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php for multi-dimensional arrays Method of summing a certain column

In PHP, you can use array_column() and array_sum() to sum a certain column of a multi-dimensional array.

1. Use array_column() to obtain all elements of a specified column

array_column() can return the value of a single column in the specified array; it will be returned An array, the array value is the value of a specified column.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array(
  array(
    &#39;month&#39; => "1",
    &#39;days&#39; => 31,
  ),
  array(
    &#39;month&#39; => "2",
    &#39;days&#39; => 28,
  ),
  array(
    &#39;month&#39; => "3",
    &#39;days&#39; => 31,
  ),
  array(
    &#39;month&#39; => "4",
    &#39;days&#39; => 30,
  ),
  array(
    &#39;month&#39; => "5",
    &#39;days&#39; => 31,
  )
);
var_dump($arr);
$days=array_column($arr, &#39;days&#39;);
var_dump($days);
?>
Copy after login

How to sum a column of a multidimensional array in php

2. Use array_sum() to sum the result array

array_sum() function can calculate all elements in the specified array The sum of

echo "多维数组中days列的和:".array_sum($days);
Copy after login

How to sum a column of a multidimensional array in php

we use a calculator to check:

How to sum a column of a multidimensional array in php

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How to sum a column of a multidimensional array in php. For more information, please follow other related articles on the PHP Chinese website!

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!