层次树按字母排序

时间:2019-07-11 18:29:53

标签: php arrays tree hierarchy alphabetical

当前代码运行良好。但是可以将主数组的第一个字母放在单词上方吗?并且不要重复下面的“更多”一词。作为下面的例子。 G,M,W ...和其他(如果有) 谢谢您的帮助。我不知道我是否解释正确。

G
Good

M 
Men
  ╚═►Watches
     ╚═►Rolex

More

W 
Women
  ╚═►Bras
     ╚═►Bedroom  
  ╚═►Jackets

使用下面的代码php。

    /**
 * Heres your categories array structure, they can be in any order as we will sort them into an hierarchical structure in a moment
 */
$categories = array();
$categories[] = array('id'=>9, 'parent_id' => 0, 'name' => 'More', 'slug' => 'more', 'status' => 1);
$categories[] = array('id'=>8, 'parent_id' => 0, 'name' => 'Good', 'slug' => 'good', 'status' => 1);
$categories[] = array('id'=>5, 'parent_id' => 4, 'name' => 'Bedroom wear', 'slug' => 'bwear', 'status' => 1);
$categories[] = array('id'=>6, 'parent_id' => 3, 'name' => 'Rolex', 'slug' => 'rolex', 'status' => 1);
$categories[] = array('id'=>1, 'parent_id' => 0, 'name' => 'Men', 'slug' => 'men', 'status' => 1);
$categories[] = array('id'=>2, 'parent_id' => 0, 'name' => 'Women', 'slug' => 'women', 'status' => 1);
$categories[] = array('id'=>3, 'parent_id' => 1, 'name' => 'Watches', 'slug' => 'watches', 'status' => 1);
$categories[] = array('id'=>4, 'parent_id' => 2, 'name' => 'Bras', 'slug' => 'bras', 'status' => 1);
$categories[] = array('id'=>7, 'parent_id' => 2, 'name' => 'Jackets', 'slug' => 'jackets', 'status' => 1);


/**
 * This function takes the categories and processes them into a nice tree like array
 */
function preprocess_categories($categories) {

    // First of all we sort the categories array by parent id!
    // We need the parent to be created before teh children after all?
    $parent_ids = array();
    foreach($categories as $k => $cat) {
        $parent_ids[$k] = $cat['parent_id'];
        $main_nm[$k] = $cat['name'];
    }
    //array_multisort($parent_ids, SORT_ASC, $categories);
    array_multisort($parent_ids, SORT_ASC, $main_nm, SORT_ASC, $categories);

    /* note: at this point, the categories are now sorted by the parent_id key */

    // $new contains the new categories array which you will pass into the tree function below (nothign fancy here)
    $new = array();

    // $refs contain references (aka points) to places in the $new array, this is where the magic happens!
    // without references, it would be difficult to have a completely random mess of categories and process them cleanly
    // but WITH references, we get simple access to children of children of chilren at any point of the loop
    // each key in this array is teh category id, and the value is the "children" array of that category
    // we set up a default reference for top level categories (parent id = 0) 
    $refs = array(0=>&$new);

    // Loop teh categories (easy peasy)
    foreach($categories as $c) {

        // We need the children array so we can make a pointer too it, should any children categories popup
        $c['children'] = array();

        // Create the new entry in the $new array, using the pointer from $ref (remember, it may be 10 levels down, not a top level category) hence we need to use the reference/pointer
        $refs[$c['parent_id']][$c['id']] = $c;

        // Create a new reference record for this category id
        $refs[$c['id']] = &$refs[$c['parent_id']][$c['id']]['children'];

    }

    return $new;

}

/**
 * This function generates our HTML from the categories array we have pre-processed
 */
function tree($categories, $baseurl = '/category/') {

     $tree = "<ul>";

     foreach($categories as $category) {

        $tree .= "<li>";

        $tree .= "<a href='".$baseurl.$category['slug']."'>".$category['name']."</a>";

        // This is the magci bit, if there are children categories, the function loops back on itself
        // and processes the children as if they were top level categories
        // we append the children to the main tree string rather tha echoing for this reason
        // we also pass the base url PLUS our category slug as the "new base url" so it can build the URL correctly
        if(!empty($category['children'])) {

            $tree .= tree($category['children'], $baseurl.$category['slug'].'/');

        }

        $tree .= "</li>";


     }

     $tree .= "</ul>";

     return $tree;

}

///echo "<pre>"; print_r(preprocess_categories($categories)); die();
echo tree( preprocess_categories( $categories ) );

1 个答案:

答案 0 :(得分:0)

我认为处理此问题的最简单方法是再遍历$new数组一次。我在下面对您的代码进行了快速编辑。最后将其放在preprocess_categories函数中。请记住删除代码中的return $new;行。随附的代码段中已经有return


    // SET A NEW DEFAULT ARRAY

    $new_by_alpha = array();

    // LOOP THROUGH THE $new ARRAY ONE MORE TIME
    // we only need to loop through the top level arrays in the main array since we will keep the children arrays intact

    foreach ( $new as $obj ) {

        // CALCULATE THE MAIN CATS FIRST CHARACTER FROM NAME

        $name   = $obj[ 'name' ];
        $alpha  = strtoupper( substr( $name , 0 , 1 ) );

        // CHECK TO SEE IF THE NEW TOP LEVEL ALPHA ID IS SET IN THE $new_by_alpha ARRAY
        // if its not set, then we create it with default variables and values

        if ( !isset( $new_by_alpha[ $alpha ] ) || empty( $new_by_alpha[ $alpha ] ) ) {

            $new_by_alpha[ $alpha ] = array(

                'id'        => $alpha,
                'name'      => $alpha,
                'slug'      => '#',
                'status'    => 1,
                'chlidren'  => array(),

            );

        }

        // NOW THAT WE ARE SURE THAT THE VERY TOP LEVEL IS SET WE CAN ADD THE FULL OBJECT TO IT

        $new_by_alpha[ $alpha ][ 'children' ][] = $obj;

    }

    return $new_by_alpha;

本质上,这是在将$new数组中的顶级数组作为对象,并在新的顶级数组中进行重组。