【问题标题】:How to create a permutation of two dimensional array [duplicate]如何创建二维数组的排列[重复]
【发布时间】:2015-07-25 09:30:30
【问题描述】:

一开始,我担心我找不到更好的题目来回答这个问题。

我有一个看起来像这样的二维数组,例如:

 [0] => Array
     (
        [0] => 10,00
     )
 [1] => Array
     (
        [0] => 3
        [1] => 4
     )
 [2] => Array
     (
        [0] => true
        [1] => false
     )

我现在想将其转换/解析成一个二维数组,如下所示:

[0] => Array
    (
        [0] => 10,00
        [1] => 3
        [2] => true
    )
[1] => Array
    (
        [0] => 10,00
        [1] => 4
        [2] => true
    )
[2] => Array
    (
        [0] => 10,00
        [1] => 3
        [2] => false
    )
[3] => Array
    (
        [0] => 10,00
        [1] => 4
        [2] => false
    )

我希望您看到,结果应该提供各种可能的组合。事实上,第一个数组的长度可以不同。

我对如何通过算法解决这个问题很感兴趣,但目前我不知道。

我不确定,这是否像看起来那样简单。提前谢谢你。

【问题讨论】:

  • 你到目前为止所尝试的。请给我们看看?
  • 为什么[2] 键中有truefalse,它代表什么以及为什么会发生变化?
  • 谢谢你,kolmar,这帮助很大

标签: php algorithm multidimensional-array


【解决方案1】:

我想这可以改进,但它应该可以解决问题:

<?php

$arrStart = array(
    array('10,00'),
    array(3, 4),
    array('true', 'false')
);

$arrPositions = array();
$arrResult = array();

//get a starting position set for each sub array
for ($i = 0; $i < count($arrStart); $i++)
    $arrPositions[] = 0;

//repeat until we've run out of items in $arrStart[0]
while (array_key_exists($arrPositions[0], $arrStart[0])) {
    $arrTemp = array();
    $blSuccess = true;

    //go through each of the first array levels
    for ($i = 0; $i < count($arrStart); $i++) {
        //is there a item in the position we want in the current array?
        if (array_key_exists($arrPositions[$i], $arrStart[$i])) {
            //add that item to our temp array
            $arrTemp[] = $arrStart[$i][$arrPositions[$i]];
        } else {
            //reset this position, and raise the one to the left
            $arrPositions[$i] = 0;
            $arrPositions[$i - 1]++;
            $blSuccess = false;
        }
    }

    //this one failed due to there not being an item where we wanted, skip to next go
    if (!$blSuccess) continue;

    //successfully adding nex line, increase the right hand count for the next one
    $arrPositions[count($arrStart) - 1]++;

    //add our latest temp array to the result
    $arrResult[] = $arrTemp;
}

print_r($arrResult);
?>

【讨论】:

    猜你喜欢
    • 2017-11-25
    • 2013-09-19
    • 2013-11-22
    • 2012-02-03
    • 2014-08-21
    • 2014-08-26
    • 2016-08-10
    • 2016-09-03
    • 2014-08-15
    相关资源
    最近更新 更多