Skip to content

Instantly share code, notes, and snippets.

@pontikis
Created July 3, 2011 12:37
Show Gist options
  • Save pontikis/1062205 to your computer and use it in GitHub Desktop.
Save pontikis/1062205 to your computer and use it in GitHub Desktop.
Create a flat list of id from tree (respecting tree display order)
<?php
/**
* Create a flat list of id (respecting tree display order).
* Assumes that $table is keeping tree structure using "id", "parent_id", "display_order" fields
* @param string $table name of the table keeping tree data
* @param integer $start_node_id the id of the start node
* @param boolean $include_start_node include (or not) the id of the start node in returning result
* @param string $f_id name of "id" field
* @param string $f_parent_id name of "parent_id" field
* @param string $f_order name of "display_order" field
* @return array
*
* LICENSE: GNU General Public License (http://www.gnu.org/copyleft/gpl.html)
*
*/
function tree_to_flat_id_list($table, $start_node_id, $include_start_node = true,
$f_id = 'id', $f_parent_id = 'parent_id', $f_order = 'display_order') {
global $dbi; // simple custom wrapper of php-ADODB
static $array_ids = array();
if ($include_start_node) {
$sql = 'SELECT * FROM ' . $table . " WHERE " . $f_id . "=" . $start_node_id;
$res = $dbi->select($sql);
if ($res === false)
trigger_error('Wrong SQL: ' . $dbi->lastSQL . ' Error: ' . $dbi->lastError, E_USER_ERROR);
$array_ids[] = $res[0][$f_id];
}
$sql = 'SELECT * FROM ' . $table;
if ($start_node_id > 0) {
$sql .= ' WHERE ' . $f_parent_id . '=' . $start_node_id;
} else {
$sql .= ' WHERE ' . $f_parent_id . ' IS NULL';
}
$sql .= ' ORDER BY ' . $f_order;
$branch = $dbi->select($sql);
if ($branch === false)
trigger_error('Wrong SQL: ' . $dbi->lastSQL . ' Error: ' . $dbi->lastError, E_USER_ERROR);
if (count($branch) > 0) {
foreach ($branch as $node) {
$array_ids[] = $node[$f_id];
tree_to_flat_id_list($table, $node[$f_id], false);
}
}
return $array_ids;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment