简体   繁体   English

如何计算/生成具有数组中所有可能值的字符串?

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

This is driving me nuts but I've been struggling with this all noon now (im in GMT+2;)). 这让我发疯,但是我整天都在为此苦苦挣扎(在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 8748表示“大小”,并且该数组中的值是“ L”和“ XL”。 OptionID 8749 could be 'Color' with Values 'Red' and 'Black'. OptionID 8749可以是“颜色”,值是“红色”和“黑色”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM