Re: Threading articles from a SQL DB using PHP
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.php archive

Re: Threading articles from a SQL DB using PHP

From: Hilarion <hilarion@SPAM.op.SMIECI.pl>
Date: Tue Sep 20 2005 - 13:57:43 CEST

> I have a table with (for brevity) 2 columns. RecID and ParentID.
>
> All absolute or generation 0 PARENT records will have a ParentID of 0
> (zero) but their children will have their parentID pointed to an
> existing parent's RecID (a parent of any generation).
>
> I want to list out the parents with all their children
> and grandchildren under them and then start listing the next parent and
> all the children and grand children under them etc.
>
> example
>
> RECID ParentID
> PARENT 1 0
> child 2 1 child of p1
> child 6 1 child of p1
> child 4 6 child of child
> child 5 4 child of child of child
> PARENT 3 0 next parent of gen 0
> child 7 3 child of p3 or RecID 3
>
>
> etc.. I want to list it in that order.
>
> When I select it of the PostgreSQL database, I get records but not in
> the above order. I have to load it into a temporary array and then put
> it into that threaded ordered. I am using PEAR:DB for access to the
> PGSQL database.
>
> How do I do this? Arrays? Maps?
>
> Can elements in maps be listed through iteration?
>
> Are there processor efficient ways to do this?

If it'd be Oracle, then you could use hierarchical query, but PostgreSQL
does not support it (AFAIK).

You could do it with recursive function retrieving children of
a specified parent (which means multiple selects on database):

<?php

function get_children( $connection, $callback_function, $parentid = 0 )
{
  $qry = 'SELECT recid, parentid, name '
       . 'FROM my_table '
       . 'WHERE parentid = ' . $parentid . ' '
       . 'ORDER BY recid '
       ;
  $data = query_the_database_in_some_way( $connection, $qry );
  if ($data===FALSE)
  {
    // Throw exception or issue warning and:
    return FALSE;
  }
  foreach( $data as $row )
  {
    call_user_func( $callback_function, $row );
    if (!get_children( $connection, $callback_function, $row['recid'] ))
      return false;
  }
  return TRUE;
}

$conn = establish_database_connection_in_some_way();

function print_results( $row )
{
  echo "<tr>\n";
  foreach( $row as $cell )
    echo '<td>' . htmlspecialchars( $cell ) . "</td>\n";
  echo "</tr>\n";
}

echo "<table>\n";
get_children( $conn, 'print_results' );
echo "</table>\n";

?>

Hilarion
Received on Tue Oct 18 02:26:04 2005