I am having trouble trying to pull my information out of MySQL in an array. I have tried it many different ways but I cannot seem to get it right. I am trying to make an unordered list and I have found a script from another post that will work for me if I can figure out this array issue. In the script you can see how the original array was created, hard coded
PHP Code:<?php
$localhost = "";
$sql_username = "";
$sql_password = "";
$database = "";
//connect to database
mysql_connect($localhost,$sql_username,$sql_password);
@mysql_select_db($database) or die("Unable to select database for some reason!");
/////////////Here is my attempt to create the array////////////
$sql = "select id, parent from test_tbl";
$result = mysql_query($sql);
$data = array();
while ($row = mysql_fetch_row($result)) {
array_push($data, $row[0], $row[1]);
}
//////////////////////Here is the original array////////////////////
/*$data = array(
array('id' => 11, 'parent' => 0),
array('id' => 22, 'parent' => 11),
array('id' => 33, 'parent' => 0),
array('id' => 44, 'parent' => 33),
array('id' => 14, 'parent' => 44),
array('id' => 13, 'parent' => 44),
array('id' => 12, 'parent' => 13),
array('id' => 10, 'parent' => 77),
array('id' => 77, 'parent' => 11),
array('id' => 88, 'parent' => 11),
array('id' => 99, 'parent' => 88),
);*/
// tree builder
// build a tree structure from the list above
function makeTree($data) {
$tree = array(
array('id' => 'root', 'parent' => -1, 'children' => array()));
$treePtr = array(0 => &$tree[0]);
foreach($data as $item){
$children = &$treePtr[$item['parent']]['children'];
$c = count($children);
$children[$c] = $item;
$children[$c]['children'] = array();
$treePtr[$item['id']] = &$children[$c];
}
return $tree;
}
// node printer
// put here whatever you want
function printNode($node) {
print("<li>{$node['id']} is son of {$node['parent']}<ul>");
foreach($node['children'] as $child)
printNode($child);
print("</ul></li>");
}
// here we go
$tree = makeTree($data);
// to see what happened
// var_dump($tree);
printNode($tree[0]);
?>





Bookmarks