php 按父子层次结构的顺序递归排序get_categories()的输出

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 按父子层次结构的顺序递归排序get_categories()的输出相关的知识,希望对你有一定的参考价值。

<?php

$categories = get_the_category();

// Assemble a tree of category relationships
// Also re-key the category array for easier
// reference
$category_tree = array();
$keyed_categories = array();

foreach( (array)$categories as $c ) {
    $category_tree[$c->cat_ID] = $c->category_parent;
    $keyed_categories[$c->cat_ID] = $c;
}

// Now loop through and create a tiered list of
// categories
$tiered_categories = array();
$tier = 0;

// This is the recursive bit
while ( !empty( $category_tree ) ) {
    $cats_to_unset = array();
    foreach( (array)$category_tree as $cat_id => $cat_parent ) {
        if ( !in_array( $cat_parent, array_keys( $category_tree ) ) ) {
            $tiered_categories[$tier][] = $cat_id;
            $cats_to_unset[] = $cat_id;
        }
    }

    foreach( $cats_to_unset as $ctu ) {
        unset( $category_tree[$ctu] );
    }
    $tier++;
}

// Walk through the tiers to order the cat objects properly
$ordered_categories = array();
foreach( (array)$tiered_categories as $tier ) {
    foreach( (array)$tier as $tcat ) {
        $ordered_categories[] = $keyed_categories[$tcat];
    }
}

// Now you can loop over them and do whatever you want
foreach( (array)$ordered_categories as $oc ) {
    echo $oc->cat_name . ' ';
}

?>

以上是关于php 按父子层次结构的顺序递归排序get_categories()的输出的主要内容,如果未能解决你的问题,请参考以下文章

MySql:按父子顺序排序

在树状通用列表中按字母数字顺序对子项进行排序的扩展方法

按层次结构和名称对具有层次结构的对象数组进行排序

递归遍历未知结构的NSDictionary

text 按层次结构脚本排序

php 递归01 利用递归实现按字典顺序全排列