【问题标题】:PHP MySql: Print Tree - Parent Child CheckboxPHP MySql:打印树 - 父子复选框
【发布时间】:2014-06-22 05:09:24
【问题描述】:

我有这个MySql 表用于放置多个新闻类别(父/子):

ID  |   NAME    |  PARENTID  | DESC |
 1  |   LINUX   |     0      | NULL |
 2  |   DEBIAN  |     1      | NULL |
 3  |   SLAX    |     1      | NULL |
 4  | SLAXLIVE  |     3      | NULL |
 5  |  SWFLIVE  |     3      | NULL |

现在我需要像这样打印到jQueryCSS3 html CheckBOX

NOTE: This is Simple Example for HTML treeview.

HTML:

<ul>
        <li>    <a href="#">Parent</a>

            <ul>
                <li>    <a href="#">Child</a>

                    <ul>
                        <li>    <<a href="#">Grand Child</a>

                        </li>
                    </ul>
                </li>
                <li>    <a href="#">Child</a>

                    <ul>
                        <li><a href="#">Grand Child</a>
                        </li>
                        <li>    <a href="#">Grand Child</a>

                            <ul>
                                <li>    <a href="#">Great Grand Child</a>

                                </li>
                                <li>    <a href="#">Great Grand Child</a>

                                </li>
                                <li>    <a href="#">Great Grand Child</a>

                                </li>
                            </ul>
                        </li>
                        <li><a href="#">Grand Child</a>
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>

PHP:

$result = mysql_query("SELECT id, name, parent FROM " . NEWS_CATS . " ORDER BY name");
    $items = array();
     while($row = mysql_fetch_array($result))
         { $items[] = array('id' => $row['id'], 'label' => $row['name'], 'parent' => $row['parent']);
     } 

我需要为每个根猫打印&lt;ul&gt;&lt;li&gt;&lt;/li&gt;&lt;/ul&gt;,并为每个父类别打印&lt;ul&gt;&lt;li&gt;&lt;ul&gt;&lt;li&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;

我如何使用PHP/MySQL 创建/打印这个:

【问题讨论】:

  • "jQuery and CSS3 html CheckBOX" - 这是bullshit bingo吗?哪些现有答案不适合您,为什么?

标签: php jquery mysql css


【解决方案1】:

使用递归!注意:下面的代码对于循环图是不安全的(节点可能不是它们自己的祖先)!

printChildren($items,0);
function printChildren(array $items, $parentId){
    foreach($items as $item){
        if($item['parent']==$parentId){
            print '<li>';
            print $item['label']; //or whatever you want about the current node
            print '<ul>';
            printChildren($items, $item['id']);
            print '</ul></li>';
        }
    }
}

【讨论】:

  • 我看到这个错误:Catchable fatal error: Argument 1 passed to printChildren() must be of the type array, null given, called in line ..
  • 您可以在您的代码之后使用此代码(因为它收集了 $items 数组)。尝试理解代码而不是简单的复制粘贴:printChildren 使用您的 $items 绘制子树(从节点 $parentId 开始)并且调用 printChildren($items,0) 导致绘制整个树(根的子树)。
猜你喜欢
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 2014-05-01
  • 1970-01-01
相关资源
最近更新 更多