问题
Let's presume I have the following 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
)
)
How could I order/permute/manipulate this array, to get an array, which contains all possible orderings of each and every sub-array, while maintaining key-value association in sub arrays?
I would need a simmilar result like this:
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:
Ok, well it took me about 6 hours to complete this, but I think I finally got it!
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);
?>
来源:https://stackoverflow.com/questions/33989174/php-order-multidimensional-array-in-every-possible-way-maintining-key-value-a