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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader
  • ¥45 谷歌浏览器出现开发者工具无法显示已创建的,但您可以调试已部署的代码。 状态代码 404, net::ERR HTTP RESPONSE CODE FAILURE
  • ¥15 chatgpt网页版侧边栏和模型切换点击没反应怎么办
  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas