0

私は、次のように子から呼び出すことができる親IDを持つカテゴリのツリー構造を作成しています。

ID | Name | ParentID
1    1      0
2    2      1
3    3      2
4    4      1

結果として:

1 = 1
2 = 1 -> 2
3 = 1 -> 2 -> 3
4 = 1 -> 4

これは、3が2の子であり、1の子であることを意味します。

このアイデアを取得しようとすると(->を使用して、どの関係が設定されているかを示します)、ループ関数のために、2年生(1-> 2)にしか到達せず、3年生(1-> 2-> 3)には到達しません私はそれのために使用します。

//put all ID's in an array
while ($row2 = $connector->fetchArray($result2)){
 $id = $row2['ID'];
 $parents[$id] = $row2['name'];
}

// show the tree-structure
while ($row = $connector->fetchArray($result)){
    if($row['parentid']!=0)echo $parents[$row['parentid']].' -> ';
    echo $row['name'].' -    ';
    echo '<br>';
}

変更したいことが2つあります。

  1. コードに、必要に応じたサイズのツリーを自動的に生成させます。
  2. whileループでは、$ resultを2回(1回は$ resultとして、もう1回は$ result2として)選択して機能させる必要があります。これらの$resultには、まったく同じデータベースクエリがあります。
    SELECT ID,name,parentid FROM categories

結果をフェッチします。これを一度だけ宣言したいのですが。



すべての良い答えをありがとう。私は最も簡単で、コードから実装までのアプローチを減らしました。

$result = $connector->query('SELECT ID,name,parentid FROM categories');

// Get an array containing the results.
$parents = array();
while ($row = $connector->fetchArray($result)){
  $id = $row['ID'];
  $parents[$id] = array('ID' => $row['ID'],'name' => $row['name'],'parentid' => $row['parentid']);
}

foreach ($parents as $id => $row){
  $pid=$id;
  $arrTmp= array();
  do {      // iterate through all parents until top is reached
    $arrTmp[]=$pid;
    $pid = $parents[$pid]['parentid'];
  }while ($pid != 0);
    $arrTmp = array_reverse($arrTmp);
  foreach($arrTmp as $id){
    echo $parents[$id]['name'].' -&gt; ';
    }
  echo '<br>';
}
4

4 に答える 4

1

PostgreSQLをデータベースとして使用している場合は、 connectby ()関数を使用してレコード セットを作成できます。

SELECT * 
FROM connectby('tableName', 'id', 'parent_id') 
    AS t(keyid text, parent_keyid text, level int);

私はこの関数が大好きで、コードで常に使用しています。非常に強力なことを非常に迅速に行うことができ、(隣接モデル) のように左/右の値を維持する必要はありません。

于 2009-08-04T23:58:17.980 に答える
1

親IDを使用して階層を作成したい場合(少数のアイテム/階層にのみ適しています)

私はあなたのコードを少し修正しました (私はそれをテストしなかったので、いくつかの構文エラーがあるかもしれません):

//put all recordsets in an array to save second query
while ($row2 = $connector->fetchArray($result2)){
  $id = $row2['ID'];
  $parents[$id] = array('name' => $row2['name'],'parent' => $row2['parentid']);
}

// show the tree-structure
foreach ($parents as $id => $row){
  $pid = $row['parentid'];
  while ($pid != 0){      // iterate through all parents until top is reached
    echo $parents[$pid]['name'].' -&gt; ';
    $pid = $parents[$pid]['parentid'];
  }
  echo $parents[$id]['name'].' -    ';
  echo '<br>';
}

あなたのコメントに答えるには:

$parents = array();
$parents[2] = array('ID'=>2,'name'=>'General','parentid'=>0); 
$parents[3] = array('ID'=>3,'name'=>'Gadgets','parentid'=>2); 
$parents[4] = array('ID'=>4,'name'=>'iPhone','parentid'=>3); 

foreach ($parents as $id => $row){
  $pid=$id;
  $arrTmp= array();
  do {      // iterate through all parents until top is reached
    $arrTmp[]=$pid;
    $pid = $parents[$pid]['parentid'];
  }while ($pid != 0);
    $arrTmp = array_reverse($arrTmp);
  foreach($arrTmp as $id){
    echo $parents[$id]['name'].' -&gt; ';
    }
  echo '<br>';
}

プリントアウト:

一般 ->

一般 -> ガジェット ->

一般 -> ガジェット -> iPhone ->

于 2009-08-04T13:37:11.350 に答える
1

OOPの方が簡単かもしれません。クエリをparentIdでソートするだけです

注: listChildren メソッドと下部の出力は、正しくリストされていることを示すためのものです。表示が重要だという質問を解釈しませんでした。

class Element {
    public $id;
    public $name;
    public $parent = null;
    public $children = array();

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

    public function addChild($element)
    {
        $this->children[$element->id] = $element;
        $element->setParent($this);
    }

    public function setParent($element)
    {
        $this->parent = $element;
    }

    public function hasChildren()
    {
        return !empty($this->children);
    }

    public function listChildren()
    {
        if (empty($this->children)) {
            return null;
        }

        $out = array();
        foreach ($this->children as $child) {
            $data = $child->id . ':' . $child->name;
            $subChildren = $child->listChildren();
            if ($subChildren !== null) {
                $data .= '[' . $subChildren . ']';
            }
            $out[] = $data;
        }
        return implode(',', $out);
    }
}

$elements = array();
$noParents = array();
while ($row = $connector->fetchArray($result)) {
    $elements[$row['id']] = $element = new Element($row['id'], $row['name']);

    if (isset($elements[$row['parent']])) {
        $elements[$row['parent']]->addChild($element);
    } else {
        $noParents[] = $element;
    }
}

foreach ($noParents as $element) {
    if ($element->hasChildren()) {
        echo "Element {$element->id} has children {$element->listChildren()}.\n";
    } else {
        echo "Element {$element->id} has no children.\n";
    }
}
于 2009-08-04T15:19:14.733 に答える