以字母顺序显示分类法名称

时间:2015-01-22 09:00:57

标签: php wordpress

我已按字母顺序显示自定义分类的类别,如下所示。

A

acategoryone
acategorytwo
acategorythree

B

bcategoryone
bcategorytwo
bcategorythree

C

categoryone
categorytwo
categorythree

代码就像这样

<?php

$groups = array();

if  ($categories) {

  foreach ($categories  as $category ) {
    $first_letter_tax = $category->name ;
    $first_letter = strtoupper( $first_letter_tax[0] );

    $groups[ $first_letter ][] = $category;

  }

}

ksort($groups);

if( !empty( $groups ) ) {

    foreach ($groups as $letter => $tags) {
        echo '<ul class="tax-name-letter '.strtolower($letter).'">';
            echo '<strong>'.$letter.'</strong><br />';

            foreach( $tags as $taxonomy ) {

                $term_link = esc_url(get_term_link( $taxonomy )); 
                echo '<li><a href="'.$term_link.'">'. $taxonomy->name . '</a></li><br />';

            }
        echo '</ul>';
    }

}
?>

我想要这样

A - C

acategoryone
acategorytwo
acategorythree    
bcategoryone
bcategorytwo
bcategorythree
categoryone
categorytwo
categorythree

D - F

dcategoryone
dcategorytwo
dcategorythree    
ecategoryone
ecategorytwo
fcategorythree

我想显示上面显示的类别。就像我想在第一个&#39; ul&#39;中显示A到C.和第二栏中的D到F ......

帮我循环。我怎么能得到这个?请帮帮我。

1 个答案:

答案 0 :(得分:0)

看看这个例子:

<?php
$groups = array('A to C'=>range('a','c'), 'D to F'=>range('d','f'));
$taxonomy = array('asdf', 'dfa', 'fasd','basdf', 'chfd','eadf', 'easdf', 'asdf','iasdf','oasdf','cafghsd','cafe');
$data_collector = array();

foreach($groups as $key=>$group) {
    $data_collector[$key] = array();
    foreach($group as $char) {            
        foreach($taxonomy as $val) {
            if( $val[0] == $char ) {
                array_push($data_collector[$key], $val);
            }
        }
    }
}

print_r( $data_collector );

<强> DEMO