簡體   English   中英

PHP-從一維數組創建多維關聯數組

[英]PHP - Creating a Multidimensional Associative Array from a Single Dimensional Array

我在php中有一個數組,如下所示:

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

我要輸出的是以下內容:

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

基本上每個數組元素都需要在其后列出所有其他數組元素。

我認為創建一個關聯的多維數組會起作用。 進行foreach循環以創建初始鍵,然后再次在單個數組中運行以獲取值。 但是我不知道如何將它們組合在一起。

單個數組中可以包含任意數量的元素。

編輯:對不起,忘記了php代碼

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

輸出為:-

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

EDIT2:剛意識到我想要的輸出是錯誤的。 應該:-

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

對不起,混淆了。

如您在示例中建議的那樣,簡單地將一個空數組的長度設置為0到7,並使用array_combine函數將當前數組與新的索引數組合並。

完美的解決方案(您現在必須以適當的方式重新索引數組):

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

輸出: -https : //eval.in/708900

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM