PHP 함수 group_by()

1 개요[ | ]

PHP 함수 group_by()
function group_by($column_name, $rows) {
	$result = [];
	$groups = distinct($rows, $column_name);
	foreach($groups as $group) {
		$result[$group] = where($rows, [$column_name=>$group]);
	}
	return $result;
}
function distinct($rows, $column_name) {
        $column_values = [];
        foreach($rows as $row) {
                $column_values[$row[$column_name]] = 1;
        }
        return array_keys($column_values);
}
function where($rows, $params) {
	$result = [];
	foreach($rows as $row) {
		$row_matched = true;
		foreach($params as $column_name => $column_value) {
			if( !array_key_exists($column_name, $row) 
			|| $row[$column_name] != $column_value ) {
				$row_matched = false;
				break;
			}
		}
		if( $row_matched ) $result[] = $row;
	}
	return $result;
}

$rows = [
	['id'=>1, 'name'=>'한놈',   'department_id'=>1, 'birth_date'=>'1999-01-01'],
	['id'=>2, 'name'=>'두시기', 'department_id'=>2, 'birth_date'=>'2000-01-01'],
	['id'=>3, 'name'=>'석삼',   'department_id'=>2, 'birth_date'=>'1999-01-01'],
	['id'=>4, 'name'=>'너구리', 'department_id'=>3, 'birth_date'=>'2000-01-01'],
];
print_r( group_by('birth_date', $rows) );

$rows = [
	['id'=>1, 'level'=>'WARN', 'message'=>'name missing'],
	['id'=>2, 'level'=>'INFO', 'message'=>'hello'],
	['id'=>3, 'level'=>'WARN', 'message'=>'duplicated id'],
	['id'=>4, 'level'=>'INFO', 'message'=>'world'],
];
print_r( group_by('level', $rows) );

2 같이 보기[ | ]

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