【问题标题】:PHP - Creating a Multidimensional Associative Array from a Single Dimensional ArrayPHP - 从一维数组创建多维关联数组
【发布时间】:2017-01-04 05:20:19
【问题描述】:

我在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
)

对不起,混淆了。

【问题讨论】:

  • 请出示您尝试过的代码。

标签: php arrays multidimensional-array


【解决方案1】:

一个完美的解决方案(你现在必须以适当的方式重新索引数组):-

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

【讨论】:

    【解决方案2】:

    按照您在示例中的建议,简单地创建一个长度为 0 到 7 的空数组,并使用 array_combine 函数将当前数组与新的索引数组合并。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 2015-11-15
      • 2014-10-03
      • 1970-01-01
      相关资源
      最近更新 更多