Quantcast
Channel: 配列タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 757

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

$
0
0

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

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)

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

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


Viewing all articles
Browse latest Browse all 757

Trending Articles