0

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!

3
  • You'll probably need to convert your stdClass to an array before you apply any filters or array functions to it: if-not-true-then-false.com/2009/… Commented Aug 25, 2011 at 4:58
  • @Php "I have an array of stdClass objects"... Commented Aug 25, 2011 at 5:58
  • @deceze Do you know of any good stores that sell reading glasses? Commented Aug 25, 2011 at 6:01

1 Answer 1

2

You could use array_filter to filter the array. Just use a callback function that uses whichever filters are enabled.

Example:

function my_filter($object)
{
    $result = true;
    if (/*max price filter enabled*/) {
        $result = $result && /* $object's price is <= max price */;
    }
    if /* more filters... */

    return $result;
}

$new_array = array_filter($my_array, "my_filter");
Sign up to request clarification or add additional context in comments.

2 Comments

Could you provide an example please?
Great thanks, I tried using a different filter for every parameter and it worked but using all in a single filter looks like a better solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.