如何在php中通过多个参数过滤数组?
我有一个非常简单的 stdClass 对象数组,每个对象看起来像这样:
object(stdClass)[408]
public 'propertyID' => string '2232' (length=4)
public 'price' => string '100000' (length=6)
public 'bedroomNumber' => string '2' (length=1)
另外,我有一个带有一些选择字段的表单,例如最低价格、最高价格和最小卧室数量,它应该根据条件过滤数组项目用户选择什么,问题是如果用户以有效的方式选择多个过滤器,我不知道如何处理,例如,如果用户只想获得最高价格为 10000 和 3 间卧室的项目。
我虽然对每个条件都使用 if
语句,但它根本没有效率(我必须做一些事情,比如如果它们仅按价格、仅卧室号码、价格和卧室以及每个可能的组合)。
有没有简单的方法可以做到这一点?
提前致谢!
I have an array of stdClass objects that are very simple, every object looks something like this:
object(stdClass)[408]
public 'propertyID' => string '2232' (length=4)
public 'price' => string '100000' (length=6)
public 'bedroomNumber' => string '2' (length=1)
Also I have a form with a few select fields like Min Price, Max Price and Min Bedroom Number, that it's supposed to filter the array items depending on what the users choose, the problem is that I don't know how to handle if the user selects multiple filters in an efficient way, for example if the user wants to get only the items with a max price of 10000 and 3 bedrooms.
I though about using if
statements for every condition but it's not efficient at all (I'd have to do something like if they're filtering by price only, bedroom number only, price and bedrooms, and every possible combination).
Is there an easy way to do this?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
array_filter
来过滤数组。只需使用使用启用的过滤器的回调函数即可。例子:
You could use
array_filter
to filter the array. Just use a callback function that uses whichever filters are enabled.Example: