make数组中的问题,例如类别,子类别和子类别的兄弟姐妹

时间:2019-11-06 10:07:17

标签: php arrays

我想基于类别,子类别和子类别的同级来创建全动态屏幕,因为我具有如下所示的数组

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'
    ), 
);

为了使这个数组我尝试了下面的功能

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);
//echo json_encode($subcategory); die();
echo json_encode(array_map("utf8_converter",$subcategory));

使用此代码,我可以得到数组上面的内容,但我想要的数组就像ID 6的位置与ID 5正确的那样,它必须制作一个对象

我已经在buildTree()中尝试了以下代码

if ($children) {
   $element['subcategories'] = $children;
}
if ($element['position_from'] != '') {
   $sibling = buildTree($elements, $element['position_from']);
   $element['sibling'] = $sibling;
}

但它不起作用。

有人可以帮我吗

0 个答案:

没有答案