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

This is your code adapted (tryed to) my 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>

I get an error:

Parse error: syntax error, unexpected '=' in D:\Web Data\mydl\admin\test1.php on line 43

This is line 43:

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

Iºm not a PHP expert, but realy do not understand that code

于 2013-01-13T10:13:04.093 に答える