在类别子类别数组中添加一些对象的问题

时间:2019-11-07 06:01:19

标签: php arrays function

我想要一个用于我的网站的类别子类别数组,为此,我做了以下功能来以格式化结构获取数据。

function select_all($con){
   $table_name ="SELECT * FROM `Category`";
   $table_name_result = mysqli_query($con,$table_name);
   $array = mysqli_fetch_all($table_name_result, MYSQLI_ASSOC);
   return $array;
}   

function buildTree(array $elements, $parentId = 0) {
   $branch = array();

   foreach ($elements as $element) {
      if ($element['parent_id'] == $parentId) {
         $children = buildTree($elements, $element['ID']);
         if ($children) {
            $element['subcategories'] = $children;
         }
         $branch[] = $element;
      }
   }       
   return $branch;
}
$select_all = select_all($con);
$subcategory = buildTree($select_all);

有了这个功能,我得到了下面给出的数组

array(
  array( 
        'ID' => '1',  
        'Name' => 'ABC', 
        'Subcategory' => '', 
        'ParentID' => '0'
  ), 
  array(
        'ID' => '2',
        'Name' => 'DEF', 
        'Subcategory' => array(
            'ID' => '3',
            'Name' => 'QFE',
            'Subcategory' => array(
                [0] => stdClass Object(
                    [ID] => 5, 
                    [categoryname] => Main Menu, 
                    [type] => redirectLink, 
                    [redirection_link] => main menu, 
                    [position] => center, 
                    [position_from] => , 
                    [parent_id] => 4, 
                    [sequence] => 0
                ),
                [1] => stdClass Object (
                    [ID] => 6, 
                    [categoryname] => In Range,  
                    [type] => screenTitle, 
                    [redirection_link] => , 
                    [position] => right, 
                    [position_from] => 5, 
                    [parent_id] => 4,
                    [sequence] => 0, 
                ),
            ), 
            'ParentID' => '2'
        ), 
        'ParentID' => '0'
  ), 
);

这很好,但是当您检查ID 6紧靠ID 5时,因此我实际上希望ID 5ID 6在一个对象中,以便我可以正确地设计屏幕

但是我找不到在buildTree()

中可以得到该条件的方式

有人可以帮我吗?

0 个答案:

没有答案