如何创建二维数组的排列 [英] How to create a permutation of two dimensional array

查看:95
本文介绍了如何创建二维数组的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

恐怕一开始,对于这个问题,我找不到更好的标题.

Initially, I am afraid, that I do not find a better title for this question.

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

I have a two dimensional array that looks like this, for example:

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

我现在想将其转换/解析为如下所示的二维数组:

i'd like now to convert/parse this into a two dimensional array that looks like this:

[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
    )

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

i hope you see, that the result should provide all sort of possible combinations. indeed, the length of the first array can differ.

我会对如何通过算法解决此问题感兴趣,但目前我还不知道.

i'd be interested in how to solve this algorithmically, but at the moment i have no idea.

我不确定这是否像看起来那样简单.预先谢谢你.

i am not sure, if this is as easy as it looks like. thank you in advance.

推荐答案

我想可以对此进行完善,但是应该可以解决问题:

I imagine this could be refined, but it should do the trick:

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

这篇关于如何创建二维数组的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆