Urgent Help Need - same function inside function but create array for their values

Discussion in 'PHP' started by sweetguyzzz, Apr 11, 2011.

  1. #1
    Hi,

    I am trying to create a function which will be able to fetch record from the database but the problem is the data is to be arrange in tree form. Means I to arrange my categories like below:

    1) Computers
    -----2)Laptops
    -----3)Keyboards
    4) Mobiles
    -----5)Samsung
    -----6)Sony

    Now assume the bullet numbering of these categories as their id in database and parent id of 1 and 4 number is null but of 2, 3, 5 and 6 as their above.

    Function I am using is below:
      function CategoryForListItem($parent_id = "") {
          $sql = empty($parent_id) ? "SELECT cat_id, cat_name, cat_level FROM category WHERE cat_parent_id IS NULL" : "SELECT cat_id, cat_name, cat_level FROM category WHERE cat_parent_id='$parent_id'";
          $result = mysql_query($sql);
          while($row = mysql_fetch_array($result)) {
            $category_list_array[] = array($row['cat_name'],$row['cat_id']);
            CategoryForListItem($row['cat_id']); //calling same function 
          }
        return $category_list_array;
      }
    
    Code (markup):
    This Function Returns:
    It only returns the values from first while loop that is only return two loops, first is array("Computers", 1) and second is array("Mobiles", 4) . Like this
    [COLOR="red"]array( [COLOR="darkgreen"]array("Computers",1)[/COLOR] ,  [COLOR="blue"]array("Mobiles", 4)[/COLOR] )[/COLOR]
    Code (markup):



    My Aim To Get:
    I want an array from this function and array is multidimensional array with all categories values with their id as given below:

    [COLOR="red"]array( [COLOR="green"]array("Computers",1)[/COLOR], [COLOR="darkorange"]array("Laptops",2)[/COLOR], [COLOR="blue"]array("Keyboards",3)[/COLOR] , and so on arrays...)[/COLOR]
    Code (markup):

    Thanks in Advance.
    Please help me as it is urgent.
     
    sweetguyzzz, Apr 11, 2011 IP
  2. leunamer

    leunamer Peon

    Messages:
    65
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
     
    function CategoryForListItem($parent_id = "") {
          $sql = "SELECT cat_id, cat_name, cat_level FROM category";
          $result = mysql_query($sql);
          while($row = mysql_fetch_array($result)) {
            $category_list_array[] = array($row['cat_name'],$row['cat_id']);       
          }
        return $category_list_array;
      }
    Code (markup):
    I think this should work since you're category is determined if its a parent category if the cat_parent_id is null or if its a sub-category if the cat_parent_id has a value.
     
    leunamer, Apr 11, 2011 IP