2

I have an array in php as follows:-

$arrEquip = array("None", "Bandolier", "Canteen", "Satchel");

What I want to output is the following:-

None
Bandolier
Bandolier; Canteen
Bandolier; Canteen; Satchel
Canteen
Canteen; Satchel
Satchel

Basically each array element needs to have every other array element listed out after it.

I thought that creating an associative multidimensional array would work. Doing a foreach loop which creates the initial keys and then running through the single array again for the values. But I don't know how to combine them all together.

The single array could have any number of elements in it.

EDIT: Sorry, forgot the php code

$arrEquip = array("None", "Bandolier", "Canteen", "Satchel");
$rowCount = count($arrEquip);
$keyVal = "";
$i = 0;

foreach ($arrEquip as $key) {
    $keyVal = "";
    if (strtoupper($key) !== "NONE") {
        for ($y = ($i + 1); $y < $rowCount; $y++) {
            $keyVal = $keyVal . $arrEquip[$y] . "; ";
        }
    }
    $arrOutput[$key] = $keyVal;
    $i++;
}

Output is:-

Array
(
    [None] =>
    [Bandolier] => Canteen; Satchel;
    [Canteen] => Satchel;
    [Satchel] =>
)

EDIT2: Just realised my desired output is wrong. Should be:-

Array
(
    [0] => None
    [1] => Bandolier
    [2] => Bandolier; Canteen
    [3] => Bandolier; Canteen; Satchel
    [4] => Bandolier; Satchel
    [5] => Canteen
    [6] => Canteen; Satchel
    [7] => Satchel
)

Sorry for the mix up.

MMCB
  • 23
  • 3

2 Answers2

0

Simple make one empty array 0 to 7 length as you suggest on example and use array_combine function to merge your current array with new indexed array.

0

A perfect solution (you have to re-index array in a proper manner now):-

<?php


$test = array("None", "Bandolier", "Canteen", "Satchel");

$return = uniqueCombination($test);
//echo "<pre>";print_r($return);
//Sort
sort($return);

//Pretty Print
$final_arr = array_map(function($v){ return implode("; ", $v); }, $return);

foreach ($final_arr as $key=>$val){
    if(strpos($val,$test[0].'; ') === 0){
        unset($final_arr[$key]);
    }
}
echo "<pre/>";print_r(array_values($final_arr));



function uniqueCombination($in, $minLength = 1, $max = 2000) {
    $count = count($in);
    $members = pow(2, $count);
    $return = array();
    for($i = 0; $i < $members; $i ++) {
        $b = sprintf("%0" . $count . "b", $i);
        $out = array();
        for($j = 0; $j < $count; $j ++) {
            $b{$j} == '1' and $out[] = $in[$j];
        }

        count($out) >= $minLength && count($out) <= $max and $return[] = $out;
        }
    return $return;
}
?>

Output:- https://eval.in/708900

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98