- 함수 array_sum_column()
1 JavaScript[ | ]
JavaScript
Copy
var scores = [
{ math: 10, science: 90 },
{ math: 20, science: 80 },
{ math: 30, science: 70 }
];
Array.prototype.sum = function(k) {
var sum=0
for(var i=0,len=this.length; i<len; i++){ sum+=this[i][k] }
return sum
}
console.log( scores.sum("math") ) // 60
2 PHP[ | ]
PHP
Copy
$scores = [
['math'=>10, 'science'=>90],
['math'=>20, 'science'=>80],
['math'=>30, 'science'=>70],
];
function array_sum_column($rows, $k) {
$sum = 0;
foreach($rows as $row)$sum+=$row[$k];
return $sum;
}
echo array_sum_column($scores, 'math'); # 60
PHP
Copy
function array_sum_column($rows, $k) {
return array_sum(array_map(function($row) use($k){return $row[$k];},$rows));
}
echo array_sum_column($scores, 'math'); # 60
PHP
Copy
function array_sum_column($rows, $k) {
return array_reduce($rows,function($sum,$row) use($k){return $sum + $row[$k];},0);
}
echo array_sum_column($scores, 'math'); # 60
3 같이 보기[ | ]
편집자 Jmnote Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.