douyuanliao8815 2018-03-10 10:57
浏览 30

PHP:从下到上创建数组值的组合

I have to get all the combinations of values between n number of arrays.

Here is an example:

Filters: F1, F2, F3 contain values V1, V2, V3 the desire outcome is to have a massive array of all possible combinations in a such way:

V1^F1, V1^F2

V1^F1, V1^F2, V1^F3,

V1^F1, V1^F2, V2^F3

and so on.

The rules are that I don't need to combine the values inside a filter only with the values with the other arrays.

<?php

$filterA = array('blue', 'red', 'black');
$filterB = array('s', 'm', 'l');
$filterC = array('men', 'woman');


$filters[] = $filterA;
$filters[] = $filterB;
$filters[] = $filterC;

var_dump(combinations($filters));

function combinations($arrays, $i = 0)
{
     if (!isset($arrays[$i])) 
     {
            return array();
     }
        // Exit Conditions;
        if ($i == count($arrays) - 1) 
        {
            return $arrays[$i];
        }

         // get combinations from subsequent arrays
        $tmp = combinations($arrays, $i + 1);

        $result = array();

        // concat each array from tmp with each element from $arrays[$i]
        foreach ($arrays[$i] as $v) 
        {
            foreach ($tmp as $t) 
            {
                $result[] = is_array($t) ? array_merge(array($v), $t) : array($v, $t);
            }
        }

        return $result;
}

The following code produced almost the desired code however it misses to print out the 1st variation which is with less values.

Any suggestions to modify the code to get the desired outcome?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号