"PHP 함수 group by()"의 두 판 사이의 차이

 
(같은 사용자의 중간 판 4개는 보이지 않습니다)
1번째 줄: 1번째 줄:
==개요==
==개요==
{{DISPLAYTITLE|PHP 함수 group_by()}}
{{DISPLAYTITLE:PHP 함수 group_by()}}
;PHP 함수 group_by()
;PHP 함수 group_by()
*의존성: [[distinct()]], [[where()]]
*의존성: [[distinct()]], [[where()]]
43번째 줄: 43번째 줄:
];
];
print_r( group_by('birth_date', $rows) );
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) );
</syntaxhighlight>
</syntaxhighlight>


==같이 보기==
==같이 보기==
*[[PHP 함수 distinct()]]
* [[PHP 함수 distinct()]]
*[[PHP 함수 where()]]
* [[PHP 함수 where()]]
*[[SQL GROUP BY]]
* [[SQL GROUP BY]]
* [[함수 group_by()]]


[[분류: jmphp]]
[[분류: PHP]]
[[분류: 그룹 데이터]]

2021년 11월 27일 (토) 02:31 기준 최신판

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 }}