Php 带有price参数的数组过滤器JSON数据
我有这个JSON数据,我正在使用这个代码来匹配标题。它是有效的,但现在我想更进一步,列出所有低于某个价格、高于某个价格或等于某个价格的产品Php 带有price参数的数组过滤器JSON数据,php,json,array-filter,Php,Json,Array Filter,我有这个JSON数据,我正在使用这个代码来匹配标题。它是有效的,但现在我想更进一步,列出所有低于某个价格、高于某个价格或等于某个价格的产品 $json = '[{ "id": 2042049298481, "title": "Test Product 53", "variants": [{ "id": 15733087797297, "title": "Default Title", "price": "100.00",
$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"
}]
}, {
"id": 4285596860465,
"title": "test2222",
"variants": [{
"id": 30877916921905,
"title": "Default Title",
"price": "111.00",
"sku": "no"
}]
}]';
$array = json_decode($json,1);
$filter_name ='title';
$filter_value ='Test';
$expected88 = array_filter($array, function($el) use ($filter_value, $filter_name) {
return ($el[$filter_name] >= $filter_value);
});
echo json_encode($expected88,true);
这对标题
来说是完美的,但我们希望根据变体价格
进行过滤。一个变量可能有多个价格,如果$filter\u value
大于、等于或小于,则可能出现任何情况
例如,用户可以搜索最低价格为50的产品,因此在这种情况下,如果任何变体符合标准,则它将列出这些产品,或者用户可以搜索所有变体的价格应小于50
我们试过这样做
$expected = array_filter($array, function ($var) use ($filter_value) {
return ($var[$filter_name] >= $filter_value);
});
但它没有起作用。
我们尝试了foreach并再次测试,但结果总是空的这里是可能的解决方案
$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);
});
如何为价格设置
$filter\u name
,如果没有传入,函数应该如何使用它?过滤器名称和过滤器值是用户请求的数据。对于价格,您将设置什么$filter\u name
。。。。。。。。。。