douzhi2760 2019-06-24 12:19
浏览 33
已采纳

在产品页面上的数组中显示产品属性值

I'm using the following code to retrieve and display my product attribute value on product page:

$discounts = get_post_meta( $product->id, '_my_discounts' );

_my_discount is an array containing different discounts. Each discount contains different information (min_qty, discount, type, is_flat etc). When I use echo var_dump($discounts); I get the following output (I have two discounts):

array(1) { [0]=> array(2) {
["58038e0802c2252b7f50a70d25a33ede"]=> array(7) { ["min_qty"]=> int(4) ["discount"]=> string(3) "100" ["type"]=> int(2) ["role"]=> string(3) "any" ["position"]=> string(1) "0" ["is_flat"]=> int(1) ["is_variations_sep"]=> int(0)
["007632f30006ccaac16982b779ec57ae"]=> array(7) { ["min_qty"]=> int(8) ["discount"]=> string(3) "293" ["type"]=> int(2) ["role"]=> string(3) "any" ["position"]=> string(1) "0" ["is_flat"]=> int(1) ["is_variations_sep"]=> int(0)

My question is, how do I retrieve the highest discount out of the array in ["discount"] and display it on product page? For example the above product has two discounts $100 & $293. I want to retrieve the highest of the two and display it on my product page.

I tried the following, but it didn't work:

foreach ( $discounts as $highest_discount ) : 
$discount_value = wc_get_product_terms( $product->id, $highest_discount['discount'], array( 'fields' => 'names' ) );
echo $discount_value;
endforeach;

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • doubo1711 2019-06-24 13:00
    关注

    You just need to write small function that finds which array element has the highest discount.

    function find_highest_discount($discounts){
      $max_discount=0;
      foreach($discounts as $ds0){
          if ($ds0['discount']>$max_discount) $max_discount=$ds0['discount'];
      }
      return $max_discount;
    }
    

    Usage

    $discounts = get_post_meta( $product->id, '_my_discounts' );
    $highest_discount=find_highest_discount($discounts[0]);
    

    Update: Similar function can be created to get the lowest number.

    function find_lowest_discount($discounts){
      $min_discount=array_values($discounts)[0]['discount'];
      foreach($discounts as $ds0){
          if ($ds0['discount']<$min_discount) $min_discount=$ds0['discount'];
      }
      return $min_discount;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接