在PHP中保留多维数组键的数组排列组合。

3

我已经疯狂地尝试了两天才完成这个任务,也许你可以帮助我。这是一个关于马赛投注排列的问题。每当用户进行游戏时,我会得到一个多维数组(2级)。第一级包含比赛ID,第二级包含用户为该比赛选择的三匹马。它看起来像这样:

$play = array
(
    '4' => array(7, 32),
    '8' => array(4),
    '2' => array(9),
    '12' => array('5'),
    '83' => array('10', '11', '12', ''),
    '9' => array('3'),
);

我需要知道那次游戏的所有可能组合。这可以通过以下函数轻松完成:

function permutations(array $array)
{
    switch (count($array)) {
        case 1:
            return $array[0];
            break;
        case 0:
            throw new InvalidArgumentException('Requires at least one array');
            break;
    }

    $a = array_shift($array);
    $b = permutations($array);

    $return = array();
    foreach ($a as $key => $v) {
        if(is_numeric($v))
        {
            foreach ($b as $key2 => $v2) {
                $return[] = array_merge(array($v), (array) $v2);
            }
        }
    }

    return $return;
}

这将返回一个包含所有可能组合的数组,非常美观。到目前为止一切顺利,结果如下:

Array
(
    [0] => Array
        (
            [0] => 7
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 10
            [5] => 3
        )

    [1] => Array
        (
            [0] => 7
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 11
            [5] => 3
        )

    [2] => Array
        (
            [0] => 7
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 12
            [5] => 3
        )

    [3] => Array
        (
            [0] => 32
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 10
            [5] => 3
        )

    [4] => Array
        (
            [0] => 32
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 11
            [5] => 3
        )

    [5] => Array
        (
            [0] => 32
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 12
            [5] => 3
        )

)

我的问题:我需要每匹马的数组“key”为“race ID”,而不是0、1、2、3。我需要的结果应该像这样:

Array
(
    [0] => Array
        (
            [4] => 7
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 10
            [9] => 3
        )

    [1] => Array
        (
            [4] => 7
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 11
            [9] => 3
        )

    [2] => Array
        (
            [4] => 7
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 12
            [9] => 3
        )

    [3] => Array
        (
            [4] => 32
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 10
            [9] => 3
        )

    [4] => Array
        (
            [4] => 32
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 11
            [9] => 3
        )

    [5] => Array
        (
            [4] => 32
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 12
            [9] => 3
        )

)

如何实现这个功能?我知道这是一篇较长的帖子,但我需要绘制它。我在函数递归方面遇到了问题,并且在每个循环中都完全迷失了方向。

为什么你的初始数组中有些值是数字,有些是字符串?还有那个空的是干嘛的? - Samir Talwar
因为它来自HTML复选框数组,所以用户可能会留下一些复选框为空。permutations()函数忽略不是整数的值。这不是问题 :) - Dan H
请提供一个关键字,并附上您期望创建的有效数组样例。 - Khurram Ijaz
最后一个代码块包含所需的数组结构。谢谢! - Dan H
3个回答

9

我有同样的问题,但是Danny的解决方案对我来说不太好。在内存中管理成千上万个排列组合是非常昂贵的。

这是我的解决方案:

/**
 * Calculate permutation of multidimensional array. Without recursion!
 * Ex.
 * $array = array(
 *   key => array(value, value),
 *   key => array(value, value, value),
 *   key => array(value, value),
 * );
 *
 * @copyright Copyright (c) 2011, Matteo Baggio
 * @param array $anArray Multidimensional array
 * @param function $isValidCallback User function called to verify the permutation. function($permutationIndex, $permutationArray)
 * @return mixed Return valid permutation count in save memory configuration, otherwise it return an Array of all permutations
 */
function permutationOfMultidimensionalArray(array $anArray, $isValidCallback = false) {

    // Quick exit
    if (empty($anArray))
        return 0;

    // Amount of possible permutations: count(a[0]) * count(a[1]) * ... * count(a[N])
    $permutationCount = 1;
    // Store informations about every column of matrix: count and cumulativeCount
    $matrixInfo = array();
    $cumulativeCount = 1;

    foreach($anArray as $aColumn) {

        $columnCount       = count($aColumn);
        $permutationCount *= $columnCount;

        // this save a lot of time!
        $matrixInfo[] = array(
            'count'           => $columnCount,
            'cumulativeCount' => $cumulativeCount
        );

        $cumulativeCount  *= $columnCount;
    }

    // Save the array keys
    $arrayKeys = array_keys($anArray);
    // It needs numeric index to work
    $matrix = array_values($anArray);
    // Number of column
    $columnCount = count($matrix);
    // Number of valid permutation
    $validPermutationCount = 0;
    // Contain all permutations
    $permutations = array();

    // Iterate through all permutation numbers
    for ($currentPermutation = 0; $currentPermutation < $permutationCount; $currentPermutation++) {

        for ($currentColumnIndex = 0; $currentColumnIndex < $columnCount; $currentColumnIndex++) {
            // Here the magic!
            // I = int(P / (Count(c[K-1]) * ... * Count(c[0]))) % Count(c[K])
            // where:
            // I: the current column index
            // P: the current permutation number
            // c[]: array of the current column
            // K: number of the current column
            $index = intval($currentPermutation / $matrixInfo[$currentColumnIndex]['cumulativeCount']) % $matrixInfo[$currentColumnIndex]['count'];

            // Save column into current permutation
            $permutations[$currentPermutation][$currentColumnIndex] = $matrix[$currentColumnIndex][$index];
        }

        // Restore array keys
        $permutations[$currentPermutation] = array_combine($arrayKeys, $permutations[$currentPermutation]);

        // Callback validate
        if ($isValidCallback !== false) {
            if ($isValidCallback($currentPermutation, $permutations[$currentPermutation]))
                $validPermutationCount++;
            // *** Uncomment this lines if you want that this function return all
            //     permutations
            //else
            //  unset($permutations[$currentPermutation]);
        }
        else {
            $validPermutationCount++;
        }

        // Save memory!!
        // Use $isValidCallback to check permutation, store into DB, etc..
        // *** Comment this line if you want that function return all
        //     permutation. Memory warning!!
        unset($permutations[$currentPermutation]);
    }


    if (!empty($permutations))
        return $permutations;
    else
        return $validPermutationCount;
}


//
// How to?
//

$play = array(
    '4'  => array(7, 32),
    '8'  => array(4),
    '2'  => array(9),
    '12' => array('5'),
    '83' => array('10', '11', '12', ''), // <-- It accept all values, nested array too
    '9'  => array('3'),
);


$start = microtime(true);

// Anonymous function work with PHP 5.3.0
$validPermutationsCount = permutationOfMultidimensionalArray($play, function($permutationIndex, $permutationArray){

        // Here you can validate the permutation, print it, etc...
        // Using callback you can save memory and improve performance.
        // You don't need to cicle over all permutation after generation.
        printf('<p><strong>%d</strong>: %s</p>', $permutationIndex, implode(', ', $permutationArray));

        return true; // in this case always true
    });

$stop = microtime(true) - $start;

printf('<hr /><p><strong>Performance for %d permutations</strong><br />
       Execution time: %f sec<br/>
       Memory usage: %d Kb</p>',
       $validPermutationsCount,
       $stop,
       memory_get_peak_usage(true) / 1024);

如果有更好的想法,请告诉我!

涉及IT技术。

1

这是你需要的。我已经根据需要进行了注释:

function permutations(array $array)
{
    switch (count($array)) {
        case 1:
            // Return the array as-is; returning the first item
            // of the array was confusing and unnecessary
            return $array;
            break;
        case 0:
            throw new InvalidArgumentException('Requires at least one array');
            break;
    }

    // We 'll need these, as array_shift destroys them
    $keys = array_keys($array);

    $a = array_shift($array);
    $k = array_shift($keys); // Get the key that $a had
    $b = permutations($array);

    $return = array();
    foreach ($a as $v) {
        if(is_numeric($v))
        {
            foreach ($b as $v2) {
                // array($k => $v) re-associates $v (each item in $a)
                // with the key that $a originally had
                // array_combine re-associates each item in $v2 with
                // the corresponding key it had in the original array
                // Also, using operator+ instead of array_merge
                // allows us to not lose the keys once more
                $return[] = array($k => $v) + array_combine($keys, $v2);
            }
        }
    }

    return $return;
}

看它如何运作

顺便说一下,递归计算所有排列很好,但您可能不想在生产环境中这样做。您应该考虑进行一次健全性检查,计算有多少个排列,并且如果超过某个限制,则不允许继续处理,至少要这样做。


Jon,感谢你的出色回答。我用样本数组试过了,它运行得非常完美。但是,如果我使用这个数组,则在array_combine()中会抛出一个错误:$traits = array ( '4' => array(7, 32), '8' => array(4), '2' => array(9, 1), '12' => array(5, 78), '83' => array(10), '9' => array(3,67), ); - Dan H
问题出现在输入数组的最后一个元素包含2个或更多值时。array(3, 67)。我正在尝试修复它,但如果您找到解决方案,我会非常感激。 - Dan H

0

我通过将Jon的算法与我最初拥有的算法合并来改进了他的函数。我的做法是检查函数是否进行递归,如果是,则使用原始的array_merge()(它可以正常工作),否则使用Jon的array_combine()(以保留数组键)。

我将标记Jon的答案为正确,因为他提出了一个巧妙的解决方案,以保持数组键的完整性。

function permutations(array $array, $inb=false)
{
    switch (count($array)) {
        case 1:
            // Return the array as-is; returning the first item
            // of the array was confusing and unnecessary
            return $array[0];
            break;
        case 0:
            throw new InvalidArgumentException('Requires at least one array');
            break;
    }

    // We 'll need these, as array_shift destroys them
    $keys = array_keys($array);

    $a = array_shift($array);
    $k = array_shift($keys); // Get the key that $a had
    $b = permutations($array, 'recursing');

    $return = array();
    foreach ($a as $v) {
        if(is_numeric($v))
        {
            foreach ($b as $v2) {
                // array($k => $v) re-associates $v (each item in $a)
                // with the key that $a originally had
                // array_combine re-associates each item in $v2 with
                // the corresponding key it had in the original array
                // Also, using operator+ instead of array_merge
                // allows us to not lose the keys once more
                if($inb == 'recursing')
                    $return[] = array_merge(array($v), (array) $v2);
                else
                    $return[] = array($k => $v) + array_combine($keys, $v2);
            }
        }
    }

    return $return;
}

已成功测试多种数组组合。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接