함수 array sum column()

함수 array_sum_column()

1 JavaScript[ | ]

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[ | ]

$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
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
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 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}