PHP数组组合-一对多
很抱歉,如果其他地方存在解决方案,但我找不到 我有以下数组:PHP数组组合-一对多,php,arrays,Php,Arrays,很抱歉,如果其他地方存在解决方案,但我找不到 我有以下数组: $data = array( array('a', 'b', 'c'), array('e', 'f', 'g'), array('w', 'x', 'y', 'z'), ); 我正在努力编写一个函数,该函数将给出如下数组: a e w x y z f w x y z
$data = array(
array('a', 'b', 'c'),
array('e', 'f', 'g'),
array('w', 'x', 'y', 'z'),
);
我正在努力编写一个函数,该函数将给出如下数组:
a
e
w
x
y
z
f
w
x
y
z
g
w
x
y
z
b
e
w
x
y
z
f
w
x
y
z
g
w
x
y
z
c
e
w
x
y
z
f
w
x
y
z
g
w
x
y
z
这里的主要问题是源阵列的数量及其长度一直在变化。因此,函数应该能够处理提供给它的任何数据。
我试着想出这样的办法:
function testfunc($data){
$arrayDepth = count($data);
foreach($data as $key=>$d){
foreach($d as $e){
echo $e . "\n";
if($key < $arrayDepth){
array_shift($data);
testfunc($data);
}
}
}
}
我几乎被困了一天,没有合适的解决办法。任何帮助都会很好!谢谢 是你的朋友:
function product($arrays) {
if(count($arrays) === 1) {
return $arrays[0];
}
else {
$result = array();
foreach($arrays[0] as $value) {
$result[$value] = product(array_slice($arrays, 1));
}
return $result;
}
}
非递归版本。这应该跑得快
$result = end($data);
if ($result === false)
{
return false; // or Array or what makes sense for an empty array.
}
$higherArr = prev($data);
while ($higherArr !== false)
{
// Set the orignal array to be the one that you built previously.
$orig = $result;
$result = array();
foreach ($higherArr as $higherKey)
{
$result[$higherKey] = $orig;
}
$higherArr = prev($data);
}
echo 'Finished with: ' . var_export($result, true);
到目前为止你取得了什么成就?展示一些相关的代码肯定会帮助你得到好的答案。如果你没有表明你已经考虑过这个问题,不要指望很多用户会为你提供现成的算法。我不确定我是否理解你想做什么,但解决方案似乎是一个经典的递归。只需一层一层地遍历数组,构建新的结构(这是因为数组元素的数量和深度未知)。它看起来太简单了。你的问题写得正确吗?符合所有要求吗?@Stefan Gehrig-谢谢。我现在已经为这个问题添加了细节。我想这家伙和这家伙在上同一门课:什么??!是这样吗?天哪!谢谢Felix的快速解决方案。我不知道你是否真的想得到一个数组,但是是的,这是解决问题的一种方法。不客气:)太好了,保罗!谢谢!:)
$result = end($data);
if ($result === false)
{
return false; // or Array or what makes sense for an empty array.
}
$higherArr = prev($data);
while ($higherArr !== false)
{
// Set the orignal array to be the one that you built previously.
$orig = $result;
$result = array();
foreach ($higherArr as $higherKey)
{
$result[$higherKey] = $orig;
}
$higherArr = prev($data);
}
echo 'Finished with: ' . var_export($result, true);