How to find the Cartesian product with associative arrays in PHP

1 Answer

0 votes
/**
 * Compute the Cartesian product of multiple associative arrays.
 *
 * Example:
 * [
 *   ["color" => "red", "color" => "blue"],
 *   ["size" => "S", "size" => "M"],
 * ]
 *
 * Result:
 * [
 *   ["color" => "red",  "size" => "S"],
 *   ["color" => "red",  "size" => "M"],
 *   ["color" => "blue", "size" => "S"],
 *   ["color" => "blue", "size" => "M"]
 * ]
 */

/**
 * cartesianProduct()
 * -------------------
 * Takes an array of associative arrays and returns the Cartesian product.
 */
function cartesianProduct(array $arrays)
{
    // Start with one empty combination
    $result = [[]];

    // Loop through each associative array
    foreach ($arrays as $assocArray) {

        // Temporary array to store new combinations
        $newResult = [];

        // Loop through existing combinations
        foreach ($result as $partialCombination) {

            // Loop through each key/value pair in the current associative array
            foreach ($assocArray as $key => $value) {

                // Create a new combination by adding this key/value pair
                $newCombination = $partialCombination;
                $newCombination[$key] = $value;

                // Store the new combination
                $newResult[] = $newCombination;
            }
        }

        // Replace the old result with the expanded one
        $result = $newResult;
    }

    return $result;
}


// ------------------------------------------------------------
// Example usage
// ------------------------------------------------------------

// First associative array
$colors = [
    "color" => "red",
    "color2" => "blue"
];

// Second associative array
$sizes = [
    "size" => "S",
    "size2" => "M"
];

// Third associative array
$materials = [
    "material" => "cotton",
    "material2" => "polyester"
];

// Put all arrays into one list
$inputArrays = [$colors, $sizes, $materials];

// Compute the Cartesian product
$product = cartesianProduct($inputArrays);

// Print the result
echo "Cartesian Product:\n";
foreach ($product as $combo) {
    print_r($combo);
}



/*
run:

Cartesian Product:
Array
(
    [color] => red
    [size] => S
    [material] => cotton
)
Array
(
    [color] => red
    [size] => S
    [material2] => polyester
)
Array
(
    [color] => red
    [size2] => M
    [material] => cotton
)
Array
(
    [color] => red
    [size2] => M
    [material2] => polyester
)
Array
(
    [color2] => blue
    [size] => S
    [material] => cotton
)
Array
(
    [color2] => blue
    [size] => S
    [material2] => polyester
)
Array
(
    [color2] => blue
    [size2] => M
    [material] => cotton
)
Array
(
    [color2] => blue
    [size2] => M
    [material2] => polyester
)

*/

 



answered Jul 1 by avibootz

Related questions

3 answers 167 views
2 answers 154 views
3 answers 135 views
2 answers 226 views
...