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.
如您在示例中建议的那样,简单地将一个空数组的长度设置为0到7,并使用array_combine函数将当前数组与新的索引数组合并。
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.