Reputation: 523
Currently working on the project related to Business listing. I need some help in handing category structure.
Using the table name Bus_CategoryTbl to maintain the categories & used fields are Cat_ID, Cat_Name, Cat_Slug, Cat_Level etc., In this, Cat_PID will have the Cat_ID of the parent category.
Here are the example records,
Cat_ID Cat_name Cat_Slug Cat_PID
1 Web Design web-design 0
2 PHP php 1
3 MYSQL mysql 1
4 Hotels hotels 0
5 5 Stars 5-stars 4
6 3 stars 3-stars 4
7 Le Meridian le-meridian 5
8 St Laurn Suites st-laurn-suites 5
9 Niraali Executive niraali 6
Cat_PID value 0 indicates first level parent category.
Above is the example records, above table have 3 levels. For Ex: Hotels (Cat_ID: 4) -> 5 Stars (Cat_ID: 5) -> St Laurn Suites (Cat_ID: 8)
How the acheive the above result dynamically using PHP/MySql (Levels may increased in future)? It should not utiize more CPU time. current code was written in 3 dimensional array structure using foreach, but its little confused taking more CPU time.
Can you someone help me in achieving this? TIA.
Upvotes: 0
Views: 964
Reputation: 553
Try following code
function Fname($parentId=0){
$catgArray = array();
$sql = mysql_query("SELECT * FROM Table Where Cat_PID=$parentId");
$mainCatg = mysql_fetch_array($sql);
foreach($mainCatg as $mc){
array_push($catgArray , $mc);
$subCatg = $this->Fname($mc->Cat_ID);
if (count($subCatg ) > 0) {
array_push($catgArray , $subCatg );
}
}
return $catgArray;
}
In the Result we can check the sub category levels by using is_array() function
Upvotes: 2