PHP 함수 where()

1 개요[ | ]

PHP 함수 where()
  • 커스텀 PHP 함수
function where($rows, $params) {
	$result = array();
	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;
}

2 사용 예시[ | ]

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

$selected = where($rows, array('birth_date' => '1999-01-01'));
print_r($selected);
# Array
# (
#     [0] => Array
#         (
#             [id] => 1
#             [name] => 한놈
#             [depratment_id] => 1
#             [birth_date] => 1999-01-01
#         )
# 
#     [1] => Array
#         (
#             [id] => 3
#             [name] => 석삼
#             [depratment_id] => 2
#             [birth_date] => 1999-01-01
#         )
# )

$selected = where($rows, array('birth_date'=>'2000-01-01', 'department_id'=>2));
print_r($selected);
# Array
# (
#     [0] => Array
#         (
#             [id] => 2
#             [name] => 두시기
#             [department_id] => 2
#             [birth_date] => 2000-01-01
#         )
# )

3 같이 보기[ | ]

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