-2

在此处输入图像描述

在此表中,我们使用“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
        )
)
4

2 回答 2

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'] 
  ) ;
于 2013-09-09T10:33:53.780 回答
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;
  }
于 2013-09-09T10:34:57.110 回答