Jump to content

Need help with creating child categories


bilalghouri

Recommended Posts

I really need help with creating child categories.

 

My tbl_categories (should be parent category) structure:

 

mysql> select * from tbl_categories;

+-------+---------+----------+

| catid | catname | parentid |

+-------+---------+----------+

|    69 | test    |        1 |

|    70 | a      |        0 |

|    71 | s      |        0 |

+-------+---------+----------+

 

 

My tbl_child (should be child category) structure :

 

mysql> select * from tbl_child;

+-------+----------+------------+

| catid | parentid | catname    |

+-------+----------+------------+

|    1 |        1 | child of 1 |

+-------+----------+------------+

 

 

What i need to do is:

 

Show all the child of a category which have its parent id.

i mean if child category " child of 1 " has parent id "1" , then it should be shown under parent category "test", which has parent id 1 .

 

I think you understood what i meant..

if you didnt, here is another example of what i am trying to do:

 

examplegk8.png

 

Thanks in advance for helping me  :wink:

Link to comment
Share on other sites

than why do u need parentids for both?

 

u only need one table. just set parentid to 0 when there is no parent.

catid | catname | parentid

10      main        0

12      child        10

15      child3      12

16      child5      10

17      main2      0

 

thus u can get all root categories with

SELECT * from tbl_catageories WHERE parentid=0;

 

which wud return both main and main2

to see what child categories under main wud be

SELECT * from tbl_catageories WHERE parentid=10;

 

the parentid shud also help u traverse this category tree in reverse.

Link to comment
Share on other sites

+--------+-------------+------------+

| cat_id | cat_name    | cat_parent |

+--------+-------------+------------+

|      1 | Cars        |          0 |

|      2 | Toyota      |          1 |

|      3 | Suzuki      |          0 |

|      4 | Trucks      |          1 |

|      5 | Blue Toyota |          3 |

|      6 | Red Toyota  |          1 |

|      7 | Ford        |          1 |

|      8 | Red Suzuki  |          1 |

+--------+-------------+------------+

8 rows in set (0.00 sec)

 

mysql>

 

 

is this table ok ??

 

now can you please tell me how can i show them in this way ??

 

[Top] (just a text)

|___Parent

|  |___Child1

|  |___Child2

|  |___Child3

|  |___Child4

|___Parent

|  |___Child1

|  |___Child2

|  |___Child3

|  |___Child4

 

 

???

 

would be really appreciated if you could..

Link to comment
Share on other sites

Okay I didnt test this code (just typed it in as it came into my head). but this shud do it

Using recursion

it's just building a tree.

 

first we build a function we can use for any level. and get our base/root nodes.

 

function getnodes($parentid,$what="*")
{
    nodes=array();
    $res=mysql_query("SELECT $what from categegories where parentid=$parentid");
    while($row=mysql_fetch_assoc($res))
        $nodes[]=$row;
    return $nodes;
}

$root=getnodes(0,'cat_id');

 

now comes the fun recursive part adding child nodes

 

function addchildren(&$node)
{
    $node['child']=array();
    $parentid=$node['cat_id'];
    $res=mysql_query("SELECT $what from categegories where parentid=$parentid");
    while($row=mysql_fetch_assoc($res))
        $nodes['child'][]=$row;
    foreach($node['child'] as $key => $val)
        addchild($node['child'][$key']);
}

$ok=true;
foreach($root as $key => $node)
    addchildren($root[$key]);
    

 

now u will have a tree with all the child nodes.

 

displaying the tree

 

even more fun is displaying the tree

again recursion and a new array

function buildtree($node,$level)
{
    $marker=($level)?str_repeat('-',$level):'';
    $tree=array();
    $ctr=0;
    foreach($node as $leaf)
    {
        $tree[$ctr][0]=$marker . $leaf['cat_name'];
        $tree[$ctr++][1]=$leaf['cat_id'];
        if(!empty($leaf['child'])
        {
            $branch=buildtree($leaf['child'],$level+1);
            $tree=array_merge($tree,$branch);
        }
    }
    return $tree;
}
    
$tree=buildtree($root,0);

 

now u sould have an array in tree format ready for display

$ctr=1;
foreach($tree as $node)
    echo "$ctr) $node[0] ($node[1])<br>";

   

Link to comment
Share on other sites

doesnt work !!

 

gives error:

 

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ']' in /home/usr/htdocs/linkexchangesystem/2.php on line 32

 

 

<?php
include_once "init.php";

function getnodes($parentid,$what="*")
{
    $nodes=array();
    $res=mysql_query("SELECT $what from categegories where parentid=$parentid");
    while($row=mysql_fetch_assoc($res))
        $nodes[]=$row;
    return $nodes;
}

$root=getnodes(0,'cat_id');

function addchildren(&$node)
{
    $node['child']=array();
    $parentid=$node['cat_id'];
    $res=mysql_query("SELECT $what from categegories where parentid=$parentid");
    while($row=mysql_fetch_assoc($res))
        $nodes['child'][]=$row;
    foreach($node['child'] as $key => $val)
        addchild($node['child'][$key']);
}

$ok=true;
foreach($root as $key => $node)
    addchildren($root[$key]);

function buildtree($node,$level)
{
    $marker=($level)?str_repeat('-',$level):'';
    $tree=array();
    $ctr=0;
    foreach($node as $leaf)
    {
        $tree[$ctr][0]=$marker . $leaf['cat_name'];
        $tree[$ctr++][1]=$leaf['cat_id'];
        if(!empty($leaf['child'])
        {
            $branch=buildtree($leaf['child'],$level+1);
            $tree=array_merge($tree,$branch);
        }
    }
    return $tree;
}
    
$tree=buildtree($root,0);

$ctr=1;
foreach($tree as $node)
    echo "$ctr) $node[0] ($node[1])<br>";

?>

Link to comment
Share on other sites

try

<?php
function tree_wiev($a, $parent=0, $step=0){
$out = '';
$pre = '|  ';
foreach ($a as $v){
	if ($v['cat_parent'] == $parent){
		$out .= str_repeat($pre, $step).'|__'.$v['cat_name']."<br />\n".tree_wiev($a,$v['cat_id'],$step + 1);
	}
}return $out;
}

$data = array(
array('cat_id' => 1, 'cat_name' => 'Cars', 'cat_parent' => 0),
array('cat_id' => 2, 'cat_name' => 'Toyota', 'cat_parent' => 1),
array('cat_id' => 3, 'cat_name' => 'Suzuki', 'cat_parent' => 1),
array('cat_id' => 4, 'cat_name' => 'Trucks', 'cat_parent' => 0),
array('cat_id' => 5, 'cat_name' => 'Blue Toyota', 'cat_parent' => 2),
array('cat_id' => 6, 'cat_name' => 'Red Toyota', 'cat_parent' => 2),
array('cat_id' => 7, 'cat_name' => 'Ford', 'cat_parent' => 1),
array('cat_id' => 8, 'cat_name' => 'Red Suzuki', 'cat_parent' => 3));
echo tree_wiev($data);
?>

Link to comment
Share on other sites

I wudda continued to help however

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ']' in /home/usr/htdocs/linkexchangesystem/2.php on line 32

 

when u dun even attempt to fix the simplest of errors, than it's kinda pointless trying to show someone how to do something.

Link to comment
Share on other sites

<?php
function tree_wiev($a, $parent=0, $step=0){
$out = '';
$pre = '|  ';
foreach ($a as $v){
	if ($v['cat_parent'] == $parent){
		$out .= str_repeat($pre, $step).'|__'.$v['cat_name']."<br />\n".tree_wiev($a,$v['cat_id'],$step + 1);
	}
}return $out;
}

//$data = array(
array('cat_id' => 1, 'cat_name' => 'Cars', 'cat_parent' => 0),
array('cat_id' => 2, 'cat_name' => 'Toyota', 'cat_parent' => 1),
array('cat_id' => 3, 'cat_name' => 'Suzuki', 'cat_parent' => 1),
array('cat_id' => 4, 'cat_name' => 'Trucks', 'cat_parent' => 0),
array('cat_id' => 5, 'cat_name' => 'Blue Toyota', 'cat_parent' => 2),
array('cat_id' => 6, 'cat_name' => 'Red Toyota', 'cat_parent' => 2),
array('cat_id' => 7, 'cat_name' => 'Ford', 'cat_parent' => 1),
array('cat_id' => 8, 'cat_name' => 'Red Suzuki', 'cat_parent' => 3));

mysql_connect('','','');
mysql_select_db('');
$xyz = mysql_query('select * from tbl_categories');
while($row = mysql_fetch_assoc($xyz)) $data[]=$row;
echo tree_wiev($data);
?>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.