根据值的数量将数组拆分为组合

时间:2017-08-29 00:39:30

标签: php arrays

根据值的数量将以下数组拆分为不同的组合的最佳方法是什么?

[0] => 1
[1] => 5
[2] => 4
[3] => 1
[4] => Array
    (
        [0] => 1
        [1] => 9
    )
To

[0] => 1
[1] => 5
[2] => 4
[3] => 1
[4] => 1

  AND 

[0] => 1
[1] => 5
[2] => 4
[3] => 1
[4] => 9

2 个答案:

答案 0 :(得分:0)

function getCombinations($arr){
    $ret = array();

    $subs = array();

    // extract sub arrays
    $n = count($arr);
    for($i=0;$i<$n;$i++){
        if(is_array($arr[$i])){
            $subs[] = array('target'=>$i, 'values'=>$arr[$i], 'size'=>count($arr[$i]), 'counter'=>0);
            $arr[$i] = null;
        }
    }

    $subs_n = count($subs);

    if($subs_n==0) // no subarrays found, return input
        return $arr;

    $finished = false;
    while(!$finished){

        $combination = $arr; // this will copy the existing array
        for($i=0;$i<$subs_n;$i++){
            $combination[$subs[$i]['target']] = $subs[$i]['values'][$subs[$i]['counter']]; // write current combination into designated index
        }
        $ret[] = $combination; // add combination to output

        $carry = true;
        $i = 0;
        while($carry){
            $subs[$i]['counter']++; //next combination
            if($subs[$i]['counter']>=$subs[$i]['size']){ // if end of combination, increment next level
                $carry = true;
                $subs[$i]['counter'] = 0;
            }else{
                $carry = false;
            }
            $i++;
            if($i>=$subs_n && $carry){ // if last combination reached, all done
                $finished = true;
                $carry = false;
            }
        }
    }


    return $ret;
}

答案 1 :(得分:0)

我会选择这样的事情:

<?php

$arr = [
0 => 1,
1 => 5,
2 => 4,
3 => 1,
4 => [
        0 => 1,
        1 => 9,
    ]
];


$arr = [
    0 => null,
    1 => $arr,
];

function split_array($a) {
    $ended = true;
    $new_line = [];
    $rem_line = [];

    $last_line = array_pop($a);

    foreach ($last_line as $k=>$v){
        if ( is_array( $v ) ) {
            $new_v = array_shift($v);           
            if ( count($v) > 0 ) {
                $rem_v = $v;
                $ended = false;
            } else {
                $rem_v = $new_v;
            }
        } else {
            $new_v = $v;
            $rem_v = $v;
        }
        $new_line[] = $new_v;
        $rem_line[] = $rem_v;
    }

    $a[] = $new_line;
    if ( ! $ended ) {
        echo 'not ended';
        $a[] = $rem_line;
        $a = split_array($a);
    }


    return $a;
}

array_shift($arr);

echo '<pre>';
print_r( split_array($arr) );
echo '</pre>';