부모,자식노드 그룹화처리

부모와 연관있는 데이타는 모두 자식노드로 계속 그룹화되어 처리됨.
장점 : DB에서 정보를 가져올 시 연관있는 데이타를 매번 DB쿼리로 자식정보를 뽑지 않아도 됨.
유의사항 : 데이타가 많을경우 권장하지 않음. 소량의 데이타를 가공시 유용함

 

저장된 값 : 
N_CODE : 부모 또는 자신의 노드
C_RELATE : 자식노드
------------------------------------------------------------------------
원본 :
------------------------------------------------------------------------
Array
(
    [0] => Array
        (
            [N_CODE] => 1022
            [C_RELATE] => 0
        )
    [1] => Array
        (
            [N_CODE] => 1023
            [C_RELATE] => 1022
        )
    [2] => Array
        (
            [N_CODE] => 1024
            [C_RELATE] => 1022
        )
    [3] => Array
        (
            [N_CODE] => 1025
            [C_RELATE] => 0
        )
    [4] => Array
        (
            [N_CODE] => 1027
            [C_RELATE] => 1025
        )

    [5] => Array
        (
            [N_CODE] => 1028
            [C_RELATE] => 1025
        )
)
------------------------------------------------------------------------
결과 :
------------------------------------------------------------------------
Array
(
    [0] => Array
        (
            [N_CODE] => 1022
            [C_RELATE] => 0
            [children] = Array
                (
                     [0] => Array
                         (
                            [N_CODE] => 1023
                            [C_RELATE] => 1022
                         )
                     [1] => Array
                         (
                            [N_CODE] => 1024
                            [C_RELATE] => 1022
                         )
                )
        )
    [1] => Array
        (
            [N_CODE] => 1025
            [C_RELATE] => 0
            [children] = Array
                (
                     [0] => Array
                         (
                            [N_CODE] => 1027
                            [C_RELATE] => 1025
                         )
                     [1] => Array
                         (
                            [N_CODE] => 1028
                            [C_RELATE] => 1025
                         )
                )
        )
)
------------------------------------------------------------------------
// $items : 원본 배열값

 

방법1)

function buildMenu($items) {
	$childs = array();
	foreach($items as &$item) $childs[(int)$item['C_RELATE']][] = &$item;
	unset($item);
	foreach($items as &$item) if (isset($childs[$item['N_CODE']]))
	$item['children'] = $childs[$item['N_CODE']];
	
	return $childs;
}

 

방법2)

function buildMenu($items) {
	$childs = array();
	foreach($items as &$item) $childs[(int)$item['C_RELATE']][] = &$item;
	unset($item);
	foreach($items as &$item) if (isset($childs[$item['N_CODE']]))
	$item['children'] = $childs[$item['N_CODE']];
	$datas = array();
	foreach($childs as $data) array_push($datas, $data);
	$datas = array_unique($datas);
	unset($items);
	return array_pop($datas);
}