Как скомбинировать значения неограниченного количества массивов или декартово произведение множеств

function cartesian(array $set): array
{
    $result = [];

    if (!$set) {
        $result[] = [];

        return $result;
    }

    $head = array_shift($set);

    $tails = cartesian($set);

    foreach ($head as $headValue) {
        foreach ($tails as $tail) {
            array_unshift($tail, $headValue);

            $result[] = $tail;
        }
    }

    return $result;
}

$set = [
    [1, 2],
    ['A', 'B'],
    ['+', '-'],
];

print_r(cartesian($set));

/*
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => A
            [2] => +
        )

    [1] => Array
        (
            [0] => 1
            [1] => A
            [2] => -
        )

    [2] => Array
        (
            [0] => 1
            [1] => B
            [2] => +
        )

    [3] => Array
        (
            [0] => 1
            [1] => B
            [2] => -
        )

    [4] => Array
        (
            [0] => 2
            [1] => A
            [2] => +
        )

    [5] => Array
        (
            [0] => 2
            [1] => A
            [2] => -
        )

    [6] => Array
        (
            [0] => 2
            [1] => B
            [2] => +
        )

    [7] => Array
        (
            [0] => 2
            [1] => B
            [2] => -
        )

)
*/