PHP - 以各种可能的方式对多维数组进行排序,保证键值关联

时间:2015-11-29 22:59:14

标签: php multidimensional-array

我们假设我有以下数组:

Array
(
    [0] => Array
        (
            [2] => 0
            [1] => 0
            [0] => 0
        )

    [1] => Array
        (
            [2] => 1
            [1] => 0
            [0] => 0
        )

    [2] => Array
        (
            [2] => 1
            [1] => 2
            [0] => 0
        )
)

我如何命令/置换/操纵这个数组,以获得一个数组,其中包含每个子数组的所有可能的排序,同时保持子数组中的键值关联?

我需要像这样的类似结果:

Array
(
    [0] => Array
        (
            [2] => 0
            [1] => 0
            [0] => 0
        )

    [1] => Array
        (
            [1] => 0
            [2] => 0
            [0] => 0
        )

    [2] => Array
        (
            [1] => 0
            [0] => 0
            [2] => 0
        )

    [3] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
        )
     ...
    [x] => Array
       (
           [0] => 0
           [2] => 1
           [1] => 2
       )
)

1 个答案:

答案 0 :(得分:1)

好吧,我花了大约6个小时来完成这个,但我想我终于明白了!

PHP Fiddle

<?php

    function cycle($items, $perms=[]) {     

        global $begin_array, $working_array, $count;

        if (empty($items)) {

            $compiled = [];

            foreach($perms as $key){                    
                $compiled[$key] = $begin_array[$count][$key];                   
            }

            $working_array[] = $compiled;


        }  else {

            for ($i = count($items) - 1; $i >= 0; --$i) {

                 $newitems = $items;
                 $newperms = $perms;

                 list($list) = array_splice($newitems, $i, 1);                   
                 array_unshift($newperms, $list);

                 cycle($newitems, $newperms);

             }

        }


    }

    function permute($items_array){

        global $count, $working_array;              

        foreach($items_array as $item_array){

            $by_array_keys = array_keys($item_array);

            cycle($by_array_keys);      

            $final_array[] = $working_array[$count];

            ++$count;

        }


    }

    $count = 0;

    $begin_array = [

        0 => [
            0 => 'A0',
            1 => 'A1',
            2 => 'A2'
        ],

        1 => [
            0 => 'B0',
            1 => 'B1',
            2 => 'B2'
        ],

    ];      

    $working_array = [];

    $final_array = [];

    permute($begin_array);

    print_r($working_array);

?>