>  기사  >  백엔드 개발  >  PHP 무한 분류 코드 문제

PHP 무한 분류 코드 문제

WBOY
WBOY원래의
2016-09-27 14:18:10839검색

무한분류를 작성하려고 했는데 몇 가지 문제가 있었습니다. 오랫동안 고민한 결과 코드는 괜찮다고 느꼈으나 결과가 틀렸습니다. 이제 다들 혼란스러워지네요....

온라인에서 밤을 좀 읽어보니 글쓰기 방식이 나와 다른 것 같더군요.


배열 구조는 다음과 같습니다.

<code>Array
(
    [0] => Array
        (
            [id] => 1
            [name] => 代码
            [parent] => 0
        )

    [1] => Array
        (
            [id] => 3
            [name] => 动漫
            [parent] => 0
        )

    [2] => Array
        (
            [id] => 4
            [name] => 治愈
            [parent] => 3
        )

    [3] => Array
        (
            [id] => 5
            [name] => 励志
            [parent] => 3
        )

    [4] => Array
        (
            [id] => 6
            [name] => 机战
            [parent] => 3
        )

    [5] => Array
        (
            [id] => 7
            [name] => 百合
            [parent] => 3
        )

    [6] => Array
        (
            [id] => 8
            [name] => 资源
            [parent] => 0
        )

    [7] => Array
        (
            [id] => 9
            [name] => app
            [parent] => 8
        )

    [8] => Array
        (
            [id] => 10
            [name] => 软件
            [parent] => 8
        )

    [9] => Array
        (
            [id] => 11
            [name] => 黑科技
            [parent] => 8
        )

)</code>

여기서 id은 카테고리의 고유 ID이고 parent는 상위 클래스 ID입니다
제가 작성한 코드는 다음과 같습니다.

<code>
    function all($id=0){

            static $_class = null;

            if(is_null($_class))
                    $_class = select();  //这个得出来的就是以上的数组结构,然后赋值给了`$_class`变量

            $result = array();
            foreach($_class as $k => $v){
                    if($v['parent'] == $id){
                            unset($_class[$k]);
                            $v = array_merge($v, $this->all($v['id']));
                            $result['child'][] = $v;
                    }
            }

            return $result;

    }

    print_r(all(0));</code>

답글 내용:

무한분류를 작성하려고 했는데 몇 가지 문제가 있었습니다. 오랫동안 고민한 결과 코드는 괜찮다고 느꼈으나 결과가 틀렸습니다. 이제 다들 혼란스러워지네요....

온라인에서 밤을 좀 읽어보니 글쓰기 방식이 나와 다른 것 같더라구요.


배열 구조는 다음과 같습니다.

<code>Array
(
    [0] => Array
        (
            [id] => 1
            [name] => 代码
            [parent] => 0
        )

    [1] => Array
        (
            [id] => 3
            [name] => 动漫
            [parent] => 0
        )

    [2] => Array
        (
            [id] => 4
            [name] => 治愈
            [parent] => 3
        )

    [3] => Array
        (
            [id] => 5
            [name] => 励志
            [parent] => 3
        )

    [4] => Array
        (
            [id] => 6
            [name] => 机战
            [parent] => 3
        )

    [5] => Array
        (
            [id] => 7
            [name] => 百合
            [parent] => 3
        )

    [6] => Array
        (
            [id] => 8
            [name] => 资源
            [parent] => 0
        )

    [7] => Array
        (
            [id] => 9
            [name] => app
            [parent] => 8
        )

    [8] => Array
        (
            [id] => 10
            [name] => 软件
            [parent] => 8
        )

    [9] => Array
        (
            [id] => 11
            [name] => 黑科技
            [parent] => 8
        )

)</code>

여기서 id은 카테고리의 고유 ID이고 parent는 상위 클래스 ID입니다
제가 작성한 코드는 다음과 같습니다.

<code>
    function all($id=0){

            static $_class = null;

            if(is_null($_class))
                    $_class = select();  //这个得出来的就是以上的数组结构,然后赋值给了`$_class`变量

            $result = array();
            foreach($_class as $k => $v){
                    if($v['parent'] == $id){
                            unset($_class[$k]);
                            $v = array_merge($v, $this->all($v['id']));
                            $result['child'][] = $v;
                    }
            }

            return $result;

    }

    print_r(all(0));</code>

unset($_class[$k]);
이 줄 제거

이 작업을 완료하기 위해 여전히 재귀를 사용하므로 여기서는 두 가지 방법을 제공합니다. 하나는 재귀적이고 다른 하나는 포인터 형식입니다.

두 번째 코드는 이해하지 못할 수도 있지만, 여러분의 학습을 돕고 다른 사람들도 쉽게 이해할 수 있도록 다음 코드를 참고하세요.

재귀 사용

<code>// 呃,我真不忍心写出这个循环那么多遍的代码,求神解救我。

function _data_to_tree(&$items, $topid = 0, $with_id = TRUE)
{
    $result = [];
    foreach($items as $v)
        if ($topid == $v['parent'])  {
            $r = $v + ['children' => _data_to_tree($items, $v['id'], $with_id)];
            if ($with_id)
                $result[$v['id']] = $r;
            else
                $result[] = $r;
        }
            
    return $result;
}
</code>

PHP의 포인터 기능 사용

<code>function _data_to_tree($items, $topid = 0, $with_id = TRUE)
{
    if ($with_id)
        foreach ($items as $item)
            $items[ $item['parent'] ]['children'][ $item['id'] ] = &$items[ $item['id'] ];
    else
        foreach ($items as $item)
                $items[ $item['parent'] ]['children'][] = &$items[ $item['id'] ];

         return isset($items[ $topid ]['children']) ? $items[ $topid ][ 'children' ] : [];
}</code>

사용

위 배열을 전달합니다. 예를 들어 최상위 ID는 0입니다.

<code>$data = [
   ['id' => 4, 'parent' => 1 , 'text' => 'Parent1'], 
   ['id' => 1, 'parent' => 0 , 'text' => 'Root'],
   ['id' => 2, 'parent' => 1 , 'text' => 'Parent2'], 
   ['id' => 3, 'parent' => 2 , 'text' => 'Sub1'], 
];
print_r ( _data_to_tree($data, 0) );

</code>

결과

<code>Array
(
    [1] => Array
        (
            [id] => 1
            [parent] => 0
            [text] => Root
            [children] => Array
                (
                    [4] => Array
                        (
                            [id] => 4
                            [parent] => 1
                            [text] => Parent1
                            [children] => Array
                                (
                                )
                        )
                    [2] => Array
                        (
                            [id] => 2
                            [parent] => 1
                            [text] => Parent2
                            [children] => Array
                                (
                                    [3] => Array
                                        (
                                            [id] => 3
                                            [parent] => 2
                                            [text] => Sub1
                                            [children] => Array
                                                (
                                                )
                                        )
                                )
                        )
                )
        )
)</code>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.