Get all child, grandchild etc nodes under parent using php with mysql query results

后端 未结 2 1229
自闭症患者
自闭症患者 2020-11-29 11:48

I\'ve been trying to figure this out but I haven\'t gotten anywhere.Hopefully someone can come to my rescue.

My problem is I\'m using adjacency list data model to pr

2条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 11:51

    Here is a way to get you further, and you can decide how you build your result array and what fields you choose to include. This is not tested, but you should see the logic.

    // connect to db
    
    // set id counter
    $ids = 0;
    
    // declare array
    $categories = new Array();
    
    // determine max ids
    $query = mysql_query("SELECT COUNT(1) AS ids FROM test");
    $result = mysql_fetch_array(query); // get result
    $count = $result['ids'];
    
    // loop through ids for parents
    for($ids = 0; $ids <= $count; $ids++) {
      $query1 = mysql_query("SELECT * FROM test WHERE id = '" . $ids . "'");
      $query2 = mysql_query("SELECT id, name, parent_id FROM test WHERE parent_id = '" . $ids . "'");
      // check if has children
      if(mysql_num_rows($query2) > 0) {
        // iterate through children and add to array
        while (mysql_fetch_array($query2) as $row) {
          $categories[$ids]['child'][$row['id']] = $row['name'];
        }
      }
      // check if has siblings
      if(mysql_num_rows($query1) > 0) {
        // iterate through children and add to array
        while (mysql_fetch_array($query2) as $row) {
          $categories[$ids]['sibling'][$row['id']] = $row['name'];
        }
      }
    }
    

提交回复
热议问题