douzhi3105 2014-03-21 19:39
浏览 47
已采纳

从返回的数组中获取密钥

I'm working in WooCommerce, but my question is related to basic PHP foreach statements.

I have a function that returns a multidimensional array. The topmost dimension, the key string is what I need. If you've familiar, $order->get_items();.

The order_item_id is stored as the key like this:

'488' => Array( /* Array stuffs */ )

That 488 is what I need. It wouldn't be a problem if the function I'm working with's foreach statement was:

foreach ($items as $k => $v)

Where I could just use $k, but it's set up as:

foreach ($items as $item)

Is there a way to set the value of the key in the array and pass it along as a parameter?

UPDATE:

Here is the function as it works.

foreach($order_items as $item) {
    $product = $order->get_product_from_item($item);
    $gc_enabled = get_post_meta($product->id, 'ignite_gift_enabled', true);
    if ( ! $gc_enabled)
        continue;
    $coupon_prefix = get_post_meta($product->id, '_coupon_prefix', true);
    if ( ! $coupon_prefix)
        $coupon_prefix = '';
    for ($x = 1; $x <= $item['qty']; $x++) { 
        $new_coupon = $this->adjust_voucher( $coupon_prefix, $mode, $msg_details, $order_id, $order_item_id, $product->id );
    }
}

$order_items is an array of items, the keys of which I need to pass along to other functions referenced, specificaly adjust_voucher.

  • 写回答

3条回答 默认 最新

  • dqrnsg6439 2014-03-21 19:43
    关注

    Just change the foreach syntax to be foreach($items as $key => $item). This would give you access to $key while not impacting any existing code in the loop which relies on $item.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题