0

此代码适用于以下数据。但结果是一个无序的 lis,我需要它作为下拉组合框。现在有没有人知道如何使用帖子中的 SQL 数据和结构来做到这一点?

SQL

CREATE TABLE IF NOT EXISTS `categories` (
  `catid` int(3) NOT NULL AUTO_INCREMENT,
  `catname` varchar(45) NOT NULL,
  `catparent` int(3) NOT NULL,
  `catorder` int(4) NOT NULL,
  `catdesc` varchar(1024) NOT NULL,
  PRIMARY KEY (`catid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

--
-- Dumping data for table `categories`
--

INSERT INTO `categories` (`catid`, `catname`, `catparent`, `catorder`, `catdesc`) VALUES
(1, 'Informática', 0, 1000, 'Computadores e acessórios'),
(2, 'Comunicações', 0, 1000, 'Sistemas de Comunicações'),
(3, 'Acessórios', 1, 2000, 'Acessórios para Computadores'),
(4, 'PABX', 2, 2000, 'Centrais telefónicas IP e TDM'),
(5, 'Controle de Acessos', 0, 1000, 'Controle de Acessos e Assiduidade'),
(6, 'Construção Civil', 0, 1000, 'Construçao Civil    ');

代码

  <?php
  include '../lib/configuration.php';

  $mysqli = new mysqli($dbhost, $dbuser, $dbpwd, $database);

  /* check connection */
  if (mysqli_connect_errno()) 
  {
      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();
  }

  $query = "SELECT * FROM categories";
  if ($result = $mysqli->query($query)) 
  {

    /* fetch associative array */
    while($row = $result->fetch_assoc())
    { 
      $arrayCategories[$row['catid']] = array("pid" => $row['catparent'], "name" =>  $row['catname']);   
    }

    //createTree($arrayCategories, 0);
    function createTree($array, $currentParent, $currLevel = 0, $prevLevel = -1) 
    {
      foreach ($array as $categoryId => $category) 
      {
        if ($currentParent == $category['pid']) 
        {                       
            if ($currLevel > $prevLevel) echo " <ul> "; 
            if ($currLevel == $prevLevel) echo " </li> ";
            echo '<li id="'.$categoryId.'" onclick=child(this.id);><span>'.$category['name'].'</span>';
            if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }
            $currLevel++; 
            createTree ($array, $categoryId, $currLevel, $prevLevel);
            $currLevel--;               
        }   
      }
      if ($currLevel == $prevLevel) echo " </li>  </ul> ";
    }   
?>
<div id="content" class="general-style1">
<?php
   if($result->num_rows!=0)
   {
  ?>
  <ul>
      <li id="0" class="root"><span>Categories</span>
      <?php createTree($arrayCategories, 0); ?>
  </li>
  </ul>
  <?php
    }
  }
  ?>
</div>
4

2 回答 2

0

这应该对您有用,但您需要修改 cat_tree_array 中的字段名称。

function cat_tree_array($items) {
    $childs = array();
    foreach ($items as &$item) {
        $item = (array) $item;
        $childs[$item['id_parent']][] = &$item;
    }
    unset($item);

    foreach ($items as &$item) {
        $item = (array) $item;
        if (isset($childs[$item['id']])) {
            $item['_subs'] = $childs[$item['id']];
        }
    }
    return $childs[0];
}

用法:

<?
// items: all data that you fetch from db (so just an array)
// e.g
// $qry = mysql_query("select * from categorys");
// while ($fch = mysql_fetch_array($qry)) $items[] = $fch;
$tree = cat_tree_array($items); 
?>

HTML 列表:

<ul>
<? foreach ($tree as $t): ?>
    <li><?=$t['category_name']?></li>
    <? if (!empty($t['_subs'])): ?>
        <ul>
            <? foreach ($t['_subs'] as $s): ?>
                <li><?=$s['category_name']?></li>
            <? endforeach; ?>
        </ul>
    <? endif; ?>
<? endforeach; ?>
</ul>

HTML 选择:

<select>
<? foreach ($tree as $t): ?>
    <option><?=$t['category_name']?></option>
    <? if (!empty($t['_subs'])): ?>
        <optgroup>
            <? foreach ($t['_subs'] as $s): ?>
                <option><?=$s['category_name']?></option>
            <? endforeach; ?>
        </optgroup>
    <? endif; ?>
<? endforeach; ?>
</select>
于 2013-01-12T14:42:41.993 回答
0

@qeremy

这是您的代码适应(尝试)我的 SQL:

<?php
  include '../lib/configuration.php';

  function cat_tree_array($items) {
      $childs = array();
      foreach ($items as &$item) {
          $item = (array) $item;
          $childs[$item['catparent']][] = &$item;
      }
      unset($item);

      foreach ($items as &$item) {
          $item = (array) $item;
          if (isset($childs[$item['id']])) {
              $item['catid'] = $childs[$item['id']];
          }
      }
      return $childs[0];
  }  

  $mysqli = new mysqli($dbhost, $dbuser, $dbpwd, $database);

  /* check connection */
  if (mysqli_connect_errno()) 
  {
      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();
  }

  $query = "SELECT * FROM categories";
  if ($result = $mysqli->query($query)) 
  {

  /* fetch associative array */
  while($row = $result->fetch_assoc())
  { 
    $tree = cat_tree_array($items);
  } 
  ?>

  <select>
  <?php foreach ($tree as $t): ?>
      <option><?php = $t['catname']?></option>
      <?php if (!empty($t['catid'])): ?>
          <optgroup>
              <?php foreach ($t['catid'] as $s): ?>
                  <option><?php = $s['catname']?></option>
              <?php endforeach; ?>
          </optgroup>
      <?php endif; ?>
  <?php endforeach; ?>
  </select>

我收到一个错误:

解析错误:语法错误,第 43 行 D:\Web Data\mydl\admin\test1.php 中的意外 '='

这是第 43 行:

  <option><?php = $t['catname']?></option>

我不是 PHP 专家,但真的不明白那段代码

于 2013-01-13T10:13:04.093 回答