제가 만든 PHP 대댓글 정렬 함수 평가 부탁드립니다.
안녕하세요 제가 만든 PHP 대댓글을 정렬하는 함수인데 평가 부탁드립니다.
어떻게 하면 최소한의 반복으로 정렬할 수 있을까 고민하며 만든 함수입니다.
함수 호출시 파라미터에 데이터, 기본키명, 부모키명, 계층정보 추가 여부(기본 false)를 넣으시면 트리형식으로 정렬하여 반환합니다.
계층정보 추가 여부는 true를 입력할 시 반환하는 배열의 depth컬럼에 몇 레벨의 계층인지 번호를 넣어줍니다.
function listing($arr, $private_key, $parent_key, $create_depth = false) {
$order = true;
$limit = count($arr);
$tmp_arr = $tmp_list = $tmp_stack = [];
$tmp_unit = $tmp_element = null;
$depth = 1;
$now_key = 0;
$comment = $unshift_comment = [];
array_multisort(array_column($arr,$private_key),SORT_ASC,SORT_NUMERIC,$arr);
foreach ($arr as $key => $value) {
$tmp_list[$value[$parent_key]][$value[$private_key]] = $value;
}
$now_key = key($tmp_list);
$tmp_element = $tmp_list[$now_key];
unset($tmp_list[$now_key]);
while ($limit > 0) {
$now_key = key($tmp_element);
if ($create_depth == true) {
$tmp_element[$now_key]['depth'] = $depth;
}
if ($order == true) {
$comment[] = $tmp_element[$now_key];
} else {
$unshift_comment[] = $tmp_element[$now_key];
}
$tmp_unit = $tmp_element[$now_key];
unset($tmp_element[$now_key]);
if (true == isset($tmp_list[$tmp_unit[$private_key]])) {
if (count($tmp_element) > 0 ) {
$tmp_stack[] = $tmp_element;
}
$tmp_element = $tmp_list[$tmp_unit[$private_key]];
$depth++;
unset($tmp_list[$tmp_unit[$private_key]]);
}
if ((count($tmp_element) < 1) && (count($tmp_stack) > 0)) {
$now_key = array_key_last($tmp_stack);
$tmp_element = $tmp_stack[$now_key];
unset($tmp_stack[$now_key]);
$depth--;
}
if ((count($tmp_element) < 1) && (count($tmp_list) > 0)) {
$order = false;
$depth = 1;
$now_key = key($tmp_list);
$tmp_element = $tmp_list[$now_key];
unset($tmp_list[$now_key]);
}
$limit--;
}
return array_merge($unshift_comment,$comment);
}