algorithm - convert my database table to a tree and get leaf nodes in php -



algorithm - convert my database table to a tree and get leaf nodes in php -

hi have database table , want set tree construction , leaf nodes of tree .

in table have preferenceid , preferenceparentid.

in case want built tree .

level 1 should fashion , music , because have preferenceparentid = 0

in 2 nd level men's clothing should under fashion because it's parent preference id fashion . , artists sholud under music .

in 3 level couture , denims should under men's clothing , african , afrobeat shoul under artists.

and want all leaf node values . in case want

couture , denims , africanandafrobeat`.

tree may grow n levels .

please help me . suggestion welcome ....................... :d

in response chauhan's linked article, i'd post much simpler solution:

// sample info (from 1 big query selecting them in 1 go) $rows = array( array('id' => 971, 'parent_id' => 3, 'label' => 'genres'), array('id' => 972, 'parent_id' => 3, 'label' => 'movie stars'), array('id' => 1, 'parent_id' => 0, 'label' => 'fashion'), array('id' => 32, 'parent_id' => 1, 'label' => 'men\'s clothing'), array('id' => 45, 'parent_id' => 32, 'label' => 'couture'), array('id' => 55, 'parent_id' => 32, 'label' => 'denims'), array('id' => 2, 'parent_id' => 0, 'label' => 'music'), array('id' => 970, 'parent_id' => 2, 'label' => 'artists'), array('id' => 1118, 'parent_id' => 970, 'label' => 'african'), array('id' => 1119, 'parent_id' => 970, 'label' => 'afrobeat'), ); // build map , collect ids $map = array(); $ids = array(); foreach ($rows $row) { // 1 utilize typical mysql_fetch_* stuff here if (!isset($map[$row['parent_id']])) { $map[$row['parent_id']] = array(); } $map[$row['parent_id']][] = $row; $ids[] = $row['id']; } // recursive helper display function helper($map, $parentid = 0) { echo '<ul>'; foreach ($map[$parentid] $entry) { printf('<li>[%s] %s', $entry['id'], $entry['label']); if (isset($map[$entry['id']])) { helper($map, $entry['id']); } echo '</li>'; } echo '</ul>'; } // create ul helper($map); // leaf nodes print_r( array_diff($ids, array_keys($map)) );

i say, that, if such database structures cannot avoided, recursive queries worst thing do, performance wise.

php algorithm data-structures

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -