我需要以以下格式构建多维数组的所有可能性的地图:
$level['A1']['E1'] = true;
$level['E1']['A1'] = true;
$level['A1']['L1'] = true;
$level['L1']['A1'] = true;
$level['A1']['E2'] = true;
$level['E2']['A1'] = true;
$level['E1']['L1'] = true;
$level['L1']['E1'] = true;
$level['E1']['E2'] = true;
$level['E2']['E1'] = true;
结果需要在从A1到A1的另一个多维数组中具有所有可能的映射,例如:
$level_maps['A1']['E1']['L1']['A1'] = true;
$level_maps['A1']['E1']['E2']['A1'] = true;
$level_maps['A1']['L1']['E1']['A1'] = true;
$level_maps['A1']['L1']['E1']['E2']['A1'] = true;
$level_maps['A1']['E2']['E1']['A1'] = true;
$level_maps['A1']['E2']['E1']['L1']['A1'] = true;
初始数组可能更大,并且我很难使用递归函数。
编辑:
我有一个具有以下功能的简单类:
private function buildMap(array $levels, $parent) {
$map = array();
foreach ($levels as $level1 => $level2_vals) {
foreach($level2_vals as $level2 => $val) {
if ($parent == $level1) {
$map[$level2] = true;
unset($levels[$level1][$level2]);
$level3 = $this->buildMap($levels, $level2);
if(!empty($level3) && $level2 != $this->end_level) {
$map[$level2] = $level3;
}
else if($level2 != $this->end_level) {
$map[$level2] = false;
}
}
}
}
return $map;
}
通过以下方式调用它:
$map[$this->start_level] = $this->buildMap($level, $this->start_level);
,但是它不能正常工作,尤其是在较大的级别上。 很抱歉,如果我不清楚,那只是在寻找一个递归函数示例开始。
答案 0 :(得分:0)
在这里它如何工作,请查看下面的示例:
<?php
$level['A1']['E1'] = true;
$level['E1']['A1'] = true;
$level['A1']['L1'] = true;
$level['L1']['A1'] = true;
$level['A1']['E2'] = true;
$level['E2']['A1'] = true;
$level['E1']['L1'] = true;
$level['L1']['E1'] = true;
$level['E1']['E2'] = true;
$level['E2']['E1'] = true;
/// generate array key
$array_keys=array();
foreach($level as $key1 =>$values)
{
foreach($values as $key2 => $values2)
{
$array_keys[]=$key1.'-'.$key2;
}
}
/// split array parent and childrent on diffrent parts
$parent='A1';
$parent_keys=array();
$children_keys=array();
foreach($level as $key =>$val)
{
foreach($val as $key2 =>$val2)
{
if($key == $parent)
$parent_keys[$key.'-'.$key2]=true;
else
$children_keys[$key.'-'.$key2]=true;
}
}
$last_array=array();
foreach($parent_keys as $key =>$va)
{
$exp=explode('-',$key);
foreach($children_keys as $key2 =>$va2)
{
$arrunique=array();
if(!strchr($key2,$exp[1])){
$exp2=explode('-',$key2);
foreach($exp as $r)
{
$arrunique[$r]=$r;
}
foreach($exp2 as $r)
{
$arrunique[$r]=$r;
}
if(in_array($exp[1].'-'.$exp2[0],$array_keys))
$last_array[implode('-',$arrunique).'-'.$exp[0]]=true;
}
}
}
foreach($last_array as $key=>$va)
{
print $key."\n";
}
您可以从沙箱中执行:LINK