PHP中的数组组合器 [英] Array combinatorics 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]],
];
我正在寻找比我的代码更有效的代码. (我的当前代码显示在下面的答案中)
I am searching for a more efficient code than mine. (My current code is presented as an answer below)
推荐答案
在这里.假设:
$array = [['x'], ['y', 'z', 'w'], ['m', 'n']];
编辑:经过一些性能测试,我得出的结论是我之前发布的解决方案比OP代码慢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]];
}
}
基本上是相同的代码,但是我尽可能使用本机函数,并且还从循环中取出了一些不必在每次迭代中执行的功能.
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屋!