2
2

More than 3 years have passed since last update.

多次元連想配列の数値の合計値を出す

Last updated at Posted at 2019-12-01

多次元連想配列の数値の合計値を出す

index.php
array(3) {
  [0]=>
  array(2) {
    ["name"]=>
    string(5) "apple"
    ["stock"]=>
    int(2)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(5) "lemon"
    ["stock"]=>
    int(4)
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(5) "orange"
    ["stock"]=>
    int(8)
  }
}

こちらの連想配列の"stock"の値を合計していきます。

処理方法は

index.php
$sum_stock = array_sum(array_column($fruits, 'stock'));

です。
array_column()で配列の単一のカラムを抽出し、その値をarray_sum()で合計するという方法です。

結果は

index.php
var_dump($sum_stock);

int(14)

以上多次元連想配列の数値の合計値を出すでした。

ご閲覧ありがとうございました。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2