在PHP阵列排列 [英] Array permutation in PHP
问题描述
考虑以下数组:
$a = [['x'], ['y', 'z', 'w'], ['m', 'n']];
如何生成以下从中数组:
How can generate following array from it:
$output=[
[[x][y][m]],
[[x][z][n]],
[[x][w][m]],
[[x][y][n]],
[[x][z][m]],
[[x][w][n]],
];
我正在寻找一种更有效的code比我的。 (我现在的code是psented如下答案$ P $)
I am searching for a more efficient code than mine. (My current code is presented as an answer below)
推荐答案
在这里,我们走了。假设:
Here we go. Assuming:
$array = [['x'], ['y', 'z', 'w'], ['m', 'n']];
编辑:经过一些性能测试,我总结我以前张贴的解决方案比OP的code慢约300%,无疑因嵌套函数调用堆栈。因此,这里是OP的做法,这是周围的改进版本的 40%的速度
After some performance testing, I concluded the solution I posted before is about 300% slower than OP's code, surely due to nested function call stacking. So here is an improved version of OP's approach, which is around 40% faster:
$count = array_map('count', $array);
$finalSize = array_product($count);
$arraySize = count($array);
$output = array_fill(0, $finalSize, []);
$i = 0;
$c = 0;
for (; $i < $finalSize; $i++) {
for ($c = 0; $c < $arraySize; $c++) {
$output[$i][] = $array[$c][$i % $count[$c]];
}
}
这是基本相同的code,但我用本地函数可能时,也拿出了一些循环功能,已经不能在每次迭代执行。
It is basically the same code but I used native functions when possible and also took out the loops some functionality that hadn't to be executed on each iteration.
这篇关于在PHP阵列排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!