0

This is driving me nuts but I've been struggling with this all noon now (im in GMT+2;)).

I want to do a fairly (I believed but realized it turned out otherwise..) simple task.

Lets say I have an array which looks like this:

Array
(
    [0] => Array
        (
            [OptionID] => 8748
            [Values] => Array
                (
                    [0] => 11614
                    [1] => 11615
                )
        )
    [1] => Array
        (
            [OptionID] => 8749
            [Values] => Array
                (
                    [0] => 11616
                    [1] => 11617
               )
        )
)

This array is for generating all possible options with a product. Lets say OptionID 8748 means 'Size' and the Values in that array are 'L' & 'XL'. OptionID 8749 could be 'Color' with Values 'Red' and 'Black'.

I want to achieve the simple task to get the four unique combinations of that product in a string like:

11614+11616 11614+11617 11615+11616 11615+11617

But then, with a different product there could be a third product option, so it should be able to work arround with an unlimited depth.

1 Answer 1

1

basically

  $result = array_cartesian(array_pluck($a, 'Values'));

and here are the helper functions:

function array_pluck($a, $key) {
    $r = array();
    foreach($a as $v)
        $r[] = $v[$key];
    return $r;
}

function array_cartesian($_) {
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = array_cartesian($_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your sir, you are my personal hero for today! Thanks a lot! +10

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.