Skip to content
Advertisement

How to generate in PHP all possible selections of items in multiple arrays to cache a filter system

I have created a filter system, You can filter results on multiple taxonomies.

For example: Show all news articles and videos that are in the categories gaming and productivity and with the tag hardware, you could make a selection like this

JavaScript

This can be represented in an array like this:

JavaScript

Now basically what I want is to get an array containing all possible combinations. So it would start like this:

JavaScript

This seems like a common enough problem, but the only combination algorithms I found so far are ones that make combinations with only one element from each array. I realize that the set of combinations that I want to create would become outrageously large incredibly fast, but is there a known approach or PHP function that I could use to generate an array like this?

Advertisement

Answer

First, use the following function to generate all possible choices:

JavaScript

Example:

JavaScript

Output:

JavaScript

Second, the function of the Cartesian product of arrays:

JavaScript

Example:

JavaScript

Output:

JavaScript

Usage in your case:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement