本文介绍了Yii中的类别层次结构(PHP / MySQL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我在这里找到了它:

我想显示该代码,但无法正常工作。

And i want to display that code, but it is not working correctly.

我得到了以下层次结构:

I got the following Hierarchy:

-Airsoft
--Scopes

仅此而已。但是代码显示:

That's all. But the code is displaying:

-Airsoft
--Scopes (So far so good)
-Scopes <--- this one should not be here!

这是代码:

public static function producten(){

        $connection=Yii::app()->db;   // assuming you have configured a "db" connection
        $sql = 'SELECT id, parent, naam FROM categories ORDER BY naam';
        $command=$connection->createCommand($sql);
        $dataReader=$command->query();

        $refs = array();

        foreach ($dataReader as $row)
        {
            $ref = & $refs[$row['id']];

            $ref['parent'] = $row['parent'];
            $ref['naam']   = $row['naam'];

            if ($row['parent'] == NULL)
            {
                $list[$row['id']] = & $ref;
            }
            else
            {
                $refs[$row['parent']]['children'][$row['id']] = & $ref;
            }
        }

        function toUL(array $array)
        {
            $html = '<ul>' . PHP_EOL;

            foreach ($array as $value)
            {
                $html .= '<li>' . $value['naam'];
                if (!empty($value['children']))
                {
                    $html .= toUL($value['children']);
                }
                $html .= '</li>' . PHP_EOL;
            }

            $html .= '</ul>' . PHP_EOL;

            return $html;
        }
        print_r($refs);
        echo toUL($refs);
    }

print_r()在其中显示:

Array ( [1] => Array ( [parent] => [naam] => Airsoft [children] => Array ( [2] => Array ( [parent] => 1 [naam] => Scopes ) ) ) [2] => Array ( [parent] => 1 [naam] => Scopes ) )

有人可以找出代码和帮助的问题吗

Can somebody figure out what's wrong with the code and help me please?

推荐答案

您可以尝试以下方法:

$connection=Yii::app()->db;   // assuming you have configured a "db" connection
$sql = 'SELECT id, parent, naam FROM categories ORDER BY naam';
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();


function createList($elements, $parentId = 0) {
        $branch = array();

        foreach ($elements as $element) {
            if ($element['parent'] == $parentId) {
                $children = createList($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }

    $list = createList($dataReader);
    CVarDumper::dump($list, 5678, true);

这篇关于Yii中的类别层次结构(PHP / MySQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 12:43