2

I found an excellent tutorial on how to filter a Multidimensional array here: PHP filter 2 dimensional array by specific key

While

$filtered = array_filter(
    $array, 
    function($v) { 
        return $v['type'] == 'folder'; 
    }
); 

does do exactly what I need in terms of only displaying the folder entries, I need to be able to filter the array based on user input.

So from the example used on the page I lised above, there would be a checkbox for folder, and for page, then depending on what the user chooses (page, folder, or both), their selection would be displayed.

The problem I am running into is that I can't seem to use a variable to store $v['type'] == 'folder'.

I am hoping to do something like:

$filtered = array_filter($array, function($v) { return $userSelections; });

I also explored the possibility of using eval() (I know it may not be the best idea, but I've tried everything else I can think of) to provide the contents of the variable, but that doesn't seem to work either.

Any advice here would be great.

Thanks.

1 Answer 1

1

That's probably because of the variable scope inside closures. Try something like the following:

$filtered = array_filter($array, 
    function($v) use ($userinput) { 
        return in_array($v['type'], $_POST['userSelections']); 
    }
);

With use you declare an outside variable as accessible from inside the closure - You make it "global" so to say.

Edit: I included the final solution from below.

Sign up to request clarification or add additional context in comments.

6 Comments

Just mark the question as solved / the answer as correct if everything works. My pleasure.
Louis, thanks for the quick reply, but how would I make this work if the user selects both Page and File? The checkbox method would be storing their selections in an array and each one would have to be used.
Check it with in_array: return in_array($v['type'], $userinput);
Perfect!! Thanks again for the quick reply. I've been banging my head against my desk for a couple days over this one.
Some things just aren't that easy to figure out even though the solution is pretty simple. But after all for something like this a page like stackoverflow exist.
|

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.