为了账号安全,请及时绑定邮箱和手机立即绑定

带有价格参数的数组过滤 JSON 数据

带有价格参数的数组过滤 JSON 数据

PHP
喵喵时光机 2022-11-04 16:40:55
我有这个 JSON 数据,我正在使用这个代码来匹配标题。它有效,但现在我想更进一步,列出所有低于某个价格、或高于某个价格或等于某个价格的产品$json = '[{    "id": 2042049298481,    "title": "Test Product 53",    "variants": [{        "id": 15733087797297,        "title": "Default Title",        "price": "100.00",        "sku": "no"    }]}, {    "id": 2196682342449,    "title": "its test yar",    "variants": [{        "id": 16385289879601,        "title": "Default Title",        "price": "144.00",        "sku": "no"    }]}, {    "id": 4175970041905,    "title": "uhjkjhkhk",    "variants": [{        "id": 30302326554673,        "title": "Default Title",        "price": "1000.00",        "sku": "10"    }]}, {    "id": 4183828791345,    "title": "kaminsss",    "variants": [{        "id": 30346449518641,        "title": "Default Title",        "price": "111.00",        "sku": "no"    }]}, {    "id": 4247884890161,    "title": "hellooo",    "variants": [{        "id": 30579860832305,        "title": "Default Title",        "price": "1111.00",        "sku": "no"    }]}, {    "id": 4248143822897,    "title": "10oct latest collection",    "variants": [{        "id": 31157780938801,        "title": "50",        "price": "111.00",        "sku": "no-1"    }, {        "id": 31157802270769,        "title": "60",        "price": "101.00",        "sku": ""    }, {        "id": 31157804761137,        "title": "70",        "price": "111.00",        "sku": ""    }]}, {    "id": 4284600746033,    "title": "18oct2019",    "variants": [{        "id": 31595410030641,        "title": "120 / black",        "price": "100.00",        "sku": "10"    }]}echo json_encode($expected88,true);这可以完美地工作,title但我们希望基于variant price. 一种变体可能有多个价格,如果$filter_value大于、等于或小于,任何人都可能出现。例如,用户可能搜索最低价格为 50 的产品,因此在这种情况下,如果任何变体符合条件,则它将列出这些产品,或者用户可以搜索所有变体的价格应低于 50。我们试过这样$expected = array_filter($array, function ($var) use ($filter_value) {    return ($var[$filter_name] >= $filter_value);});但它没有用。我们再次尝试foreach和测试,但它总是给出空结果
查看完整描述

1 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

这是可能的解决方案


$filter_name ='variants';

$filter_value = 200;

$filter_field = "price";



$expected88 = array_filter($array, function($el) use ($filter_value, $filter_name, $filter_field) {

       return ((int)$el[$filter_name][0][$filter_field] >= (int)$filter_value);

}); 


查看完整回答
反对 回复 2022-11-04
  • 1 回答
  • 0 关注
  • 89 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号