【问题标题】:Sort an Array by numerical value按数值对数组进行排序
【发布时间】:2017-12-11 23:07:56
【问题描述】:

在 WooCommerce 中,我试图在单个产品页面上输出相关产品列表。我可以检索一系列相关产品,如下所示:

<?
// Current product ID
$currentProductId = $product->get_id();
// Related products
$relatedProducts = wc_get_related_products($currentProductId);

print_r($relatedIssues);
?>

但是,这会输出如下数组,看起来是随机顺序。

Array ( [0] => 28 [1] => 27 [2] => 30 [3] => 26 ) 

如果可能的话,我想按数值从高到低排列这个数组吗?

谢谢。

【问题讨论】:

    标签: php arrays wordpress sorting woocommerce


    【解决方案1】:

    有很多方法可以做到这一点:

    选项 1:好老 rsort()

    rsort($relatedProducts, SORT_NUMERIC);

    注意:此函数将新键分配给数组中的元素。它将删除可能已分配的任何现有密钥,而不仅仅是重新排序密钥。在这种情况下这无关紧要,但当数组键对进一步处理很重要时会造成严重破坏。

    选项 2:usort()

    usort($relatedProducts, sort_desc);
    
    function sort_desc( $a, $b) {
      if ( $a === $b ) {
        return 0;
      }
      return ( $a > $b ) ? -1 : 1;
    }
    

    选项 3:wc_products_array_orderby()

    wc_products_array_orderby( $relatedProducts, $orderby = 'id', $order = 'desc' )

    您不仅可以按产品 ID 排序,还可以按title, date, modified (date), menu_order, price 排序。

    这最终会调用以下函数来根据 ID 进行排序,但会在最终输出中执行 array_reverse() 以获取 'desc' 顺序:

    /**
     * Sort by id.
     * @since  3.0.0
     * @param  WC_Product object $a
     * @param  WC_Product object $b
     * @return int
     */
    function wc_products_array_orderby_id( $a, $b ) {
        if ( $a->get_id() === $b->get_id() ) {
            return 0;
        }
        return ( $a->get_id() < $b->get_id() ) ? -1 : 1;
    }
    

    为什么要避免直接在单个产品页面模板上编写自定义相关产品布局?

    相关产品已经上钩 woocommerce_after_single_product_summary 行动 content-single-product.php 模板与 woocommerce_output_related_products 函数。

    要修改单个产品页面上相关产品的顺序,您 可以简单地用woocommerce_output_related_products_args 过滤。或者 当您在模板之外(例如侧边栏)需要它时,可以使用[related_products orderby="ID"] 短代码。

    要更改布局,我强烈建议使用和自定义 WooCommerce 模板 related.php 来自 template\single-product 文件夹而不是向content-single-product.php 添加额外的代码。

    脱离标准的 WooCommerce/WordPress 约定可能会产生代码混乱,将来更难维护、调试或升级。除了其他插件、主题或您自己的自定义代码可能想要“挂钩”到所述功能或它的 HTML 输出之外,将无法这样做。

    【讨论】:

      【解决方案2】:

      试试这个:

      usort($relatedIssues, function($a, $b) {  return ($a > $b) ? -1 : 1; });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多