如何获得底层到顶级类别数组?

时间:2013-09-09 10:29:53

标签: php mysql sql

enter image description here

在这个表中我们使用'parent_category_id'创建多级子类别然后如何使用查询或PHP代码获取这种类型的数组

预期输出:

我可以搜索category_id = 7并返回底部到顶部的levev类别

在这种情况下,10是7的孩子,7是1的孩子

Array
(   
   [0] => Array
        (
            [category_id] => 1
            [category_name] => Business Cards
        ),
   [1] => Array
        (
            [category_id] => 10
            [category_name] => One Sided
        ),
  [2] => Array
        (
            [category_id] => 7
            [category_name] => Standard
        )
)

2 个答案:

答案 0 :(得分:0)

$items = array() ;

while($row = $result->fetch_assoc()){
  $items[(int) $row['category_id']] = array(
    "category_id" => $row['category_id'],
    "category_name" => $row['category_name'] 
  ) ;
}

请注意,我在该数组中使用category_id作为索引,因此按ID搜索类别非常容易。

如果您仍需要从0开始的常规索引:

  $items[] = array(
    "category_id" => $row['category_id'],
    "category_name" => $row['category_name'] 
  ) ;

答案 1 :(得分:0)

$query = "select category_id, category_name from category_table where category_id = '$id'";

$result = mysqli_query($con, $query); //assuming you perform mysqli_connection first

$array_output = array();

$row = mysqli_fetch_assoc($result);
$array_output[] = $row;

while(!empty($row)){
   if($row['parent_category_id'] == 0) break;
   $query = "select category_id, category_name from category_table where category_id = '{$row['parent_category_id']}'";
   $result = mysqli_query($con,$query);
   $row = mysqli_fetch_assoc($result);
       $array_output[]= $row;
  }