简体   繁体   中英

Filtering a Multidimensional Array based on User Input

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM