开发者

How to calculate/generate a string with all possible values in an array?

开发者 https://www.devze.com 2023-04-03 00:53 出处:网络
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.

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开发者_StackOverflow中文版 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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号