Help us understand the problem. What is going on with this article?

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

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

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)

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

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away