tiny ‘n’ smart
database layer

Odkazy: dibi | API reference

Oznámení

Omlouváme se, provoz fóra byl ukončen

fetchTree()

před 11 lety

klok
Člen | 11

Prihazuju neco do mlyna. Vytvori to stromovou stukturu,
bez ohledu na to jak jsou setridene polozky v SELECTUu.
(resp zachova jejich poradi v ramci jednotlivych zanoreni)

snad to bude nekomu uzitecne.

function DibiResult_prototype_fetchTree(DibiResult $obj, $id, $parent_id) {

  $obj->seek(0);
  $row = $obj->fetch(FALSE);
  if (!$row) return array();  // empty resultset

  $refs = array();
  $data = NULL;

  if(!array_key_exists($id,$row) ||
       !array_key_exists($parent_id,$row)) {
    throw new InvalidArgumentException("Column '$id' or '$parent_id' is not in record");
  }

  do {
    $ref = &$refs[$row[$id]];

    $ref[$parent_id] = $row[$parent_id];
    $ref = array_merge($ref,$row);

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

  } while($row = $obj->fetch(FALSE));

  unset($ref);
  unset($refs);
  return $data;
}

Ukazka pouziti:

$r = dibi::query("SELECT * FROM [category]");
echo "<pre>";
var_dump($r->fetchTree('cid','parent'));
echo "</pre>";

Vyplodi to neco takovyho:

array(2) {
  [1]=>
  array(4) {
    ["parent"]=>
    NULL
    ["kid"]=>
    string(1) "1"
    ["name"]=>
    string(5) "item1"
    ["children"]=>
    array(1) {
      [2]=>
      array(3) {
        ["parent"]=>
        string(1) "1"
        ["kid"]=>
        string(1) "2"
        ["name"]=>
        string(8) "subitem1"
      }
    }
  }
  [3]=>
  array(3) {
    ["parent"]=>
    NULL
    ["kid"]=>
    string(1) "3"
    ["name"]=>
    string(5) "item2"
  }
}

credit: http://snipplr.com/…ay-from-sql/

Editoval klok (2. 4. 2008 18:51)