php - 在自定义 foreach 循环中按字母顺序对结果进行排序

标签 php wordpress sorting woocommerce foreach

我已经修改了一个我发现可以做我需要的函数,虽然它可以工作,但不幸的是返回的结果没有任何特定的顺序,我需要它们按字母顺序排列。

此脚本从 Woocommerce 返回子类别列表:

function get_product_subcategories_list( $category_slug ){
    $terms_html = array();
    $taxonomy = 'product_cat';
    // Get the product category (parent) WP_Term object
    $parent = get_term_by( 'slug', $category_slug, $taxonomy );
    // Get an array of the subcategories IDs (children IDs)
    $children_ids = get_term_children( $parent->term_id, $taxonomy );

    // Loop through each children IDs
    foreach($children_ids as $children_id) {
        $term = get_term( $children_id, $taxonomy ); // WP_Term object
        $term_link = get_term_link( $term, $taxonomy ); // The term link
        $thumbnail_id   = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );

        if ( is_wp_error( $term_link ) ) $term_link = '';
        // Set in an array the html formatted subcategory name/link
        $terms_html[] = '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</li></a>';
    }
    return '<ul>' . implode( $terms_html ) . '</ul>';
}

...这并不重要,但这在我的模板中:

get_product_subcategories_list( $post->post_name );

问题是 $terms_html[] 正在返回这个...

<li><a href="https://example.com/pants">Pants</a></li>
<li><a href="https://example.com/shoes">Shoes</a></li>
<li><a href="https://example.com/hats">Hats</a></li>

...但我需要它像这样按字母顺序排列:

<li><a href="https://example.com/hats">Hats</a></li>
<li><a href="https://example.com/pants">Pants</a></li>
<li><a href="https://example.com/shoes">Shoes</a></li>

最佳答案

get_term_children不提供任何排序​​方式。只需自己对数组进行排序即可。

将数组中的 ->name 作为 key 对推送。然后只需使用 ksort()。像这样:

foreach($children_ids as $children_id) {
    $term = get_term( $children_id, $taxonomy ); // WP_Term object
    $term_link = get_term_link( $term, $taxonomy ); // The term link
    $thumbnail_id   = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );

    if ( is_wp_error( $term_link ) ) $term_link = '';
    // Set in an array the html formatted subcategory name/link
    $terms_html[$term->name] = '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</li></a>';
    //          ^^ push the term name as key
}

ksort($terms_html); // sort it
return '<ul>' . implode( $terms_html ) . '</ul>';

关于php - 在自定义 foreach 循环中按字母顺序对结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65803137/

相关文章:

php - 带 HTTP1.1 的 SQL 插入

python - 如何使用numpy降序排序?

ruby - 先按值排序散列,然后按键排序

java - 快速排序数字(字符串)

php - 使用 .htaccess 绕过 Zend Framework 并在子目录中运行不同的框架

PHP使用子数组值按字母顺序对数组进行排序

php - MYSQL - 如何按时间查询数据库

php - 将标题转换为十进制后,Wordpress 按 post_title 发布顺序?

javascript - 模拟鼠标点击下拉菜单

php - wordpress - 如何从侧边栏获取页面中的php变量