php - 如果值等于,则从数组中删除项目
问题描述
在 Woocommerce 订单页面上,我有订单中的项目,我想通过这些项目循环并按产品 id排除特定项目。
$order->get_order_number();
$items = $order->get_items();
foreach( $items as $key => $value) :
$exclude = $value->get_product_id();
if( in_array($exclude, array('3404') ) {
unset($items[$key]);
}
}
endforeach;
$new_items = array_values($items);
我认为这将遍历原始数组,删除$item
who$product_id == 3404
然后重新索引。
我在这里没有运气。有什么想法吗?
解决了->
//Filter out colon cleanse duo
$items = array_filter($order->get_items(), function($item) {
return $item->get_product_id() != 3404;
});
//Randomize ids and grab one
shuffle($items);
foreach( $items as $item) :
$product_id = $item->get_product_id();
$product_name = $item->get_name();
break;
endforeach;
解决方案
你应该能够做到这一点:
$items = array_filter($order->get_items(), function($item) {
return $item->get_product_id() != 3404;
});
这会迭代$items
并像foreach
每个值一样传递给$item
. 如果回调array_filter
返回 a true
,则该值将被保留否则丢弃。
您甚至可以$order->get_items()
直接传入,而无需将项目提取到数组中。
此外,如果您需要排除多个,如您的评论中所要求的,您可以这样做:
$items = array_filter($order->get_items(), function($item) {
return !in_array($item->get_product_id(), [3404, 6890]);
});
推荐阅读
- r - 涉及使用 mlogit 的独特观察的错误
- nginx - 拒绝执行来自 '..../angular.min.js' 的脚本,因为它的 MIME 类型('application/octet_stream')是不可执行的,并且严格的 MIME 类型检查
- r - 在选择函数之外使用starts_with() 来定义向量
- if-statement - 当代码为真时必须运行时,如何避免在(if,if else)语句中对相同的代码进行两次编码?
- ios - 使用 wkebview 响应对 html 元素的触摸
- php - 将 Rest API 调用从 PHP 转换为 RUBY
- pdf - 将列表数据插入到 itext7 pdf 中的表中(xamarin android)
- c# - SHQueryRecycleBin 在 .net Core 上不起作用
- python - 为什么我不能在 FastApi swagger ui 中授权 api 调用,其中可以使用 postman 授权和调用相同的 api?
- node.js - JsonWebTokenError: jwt malformed: can't verify my Webtoken