替换对象数组中的值


Replace a value in object array

我有以下数组::

WC_Cart Object (
  [cart_contents] => Array (
    [d6f5bb0bbc] => Array (
      [product_id] => 14
      [variation_id] => 325
      [variation] => Array (
        [Your Build] => Windows
      )
      [quantity] => 1

如何将[quantity] => 1替换(更新)为[quantity] => 3:::

如有任何协助,我们将不胜感激::

更新>>更多信息。让事情变得更清楚

下面是我想访问的钩子(woococommerce_calculate_totals),以更改上面打印数组中源自print_r($this);::的值

我不知道如何创建函数,我需要用add_action( 'woocommerce_calculate_totals', 'my_quantity' ); 更新值

我曾经使用过数组&钩子之前,但这是有点超出我的联盟:::

//允许插件在计算最终总额之前挂钩并更改总额

do_action('woocommerce_calculate_totals', $this);                   
            /** 
             * Grand Total
             *
             * Based on discounted product prices, discounted tax, shipping cost + tax, and any discounts to be added after tax (e.g. store credit)
             */
$this->total = apply_filters('woocommerce_calculated_total', number_format( $this->cart_contents_total + $this->tax_total + $this->shipping_tax_total + $this->shipping_total - $this->discount_total, 2, '.', ''), $this);

这就是您想要的?

$wc_cart->cart_contents['d6f5bb0bbc']['quantity'] = 3;

访问数组和对象的几个示例:

$object->some_property
$object->{'complex'.'property'.'name'.(2*3)}
$array[12]
$array['hello']
$array[ $array_index*10 ]

有关阵列和对象的更多信息,请访问:

  • 阵列:http://php.net/manual/en/language.types.array.php
  • 对象:http://www.php.net/manual/en/language.oop5.basic.php

WordPress中有一些操作和过滤器,它们是不同的:

http://codex.wordpress.org/Function_Reference/add_actionhttp://codex.wordpress.org/Function_Reference/add_filter

在WooCommerce中,有两个名称非常相似的操作/过滤器:

  • woommerce_calculate_totals操作
  • woommerce_calculated_total过滤器

woocommerce_calculate_totals操作是用cart对象调用的,所以您应该做的(希望应该工作)是:

add_action( 'woocommerce_calculate_totals', 'my_quantity' );
function my_quantity( $wc_cart ){
  $wc_cart->cart_contents['d6f5bb0bbc']['quantity'] = 3;
}

首先从对象中取出cart_contents,然后遍历数组:

$wc_cart->cart_contents['d6f5bb0bbc']['quantity'] = 3;