2011-09-28 136 views
0

任何人都可以在这里帮助我一些编码?PHP走路和打印多维阵列

我得到了以下阵列配置:

$array[1]['areaname'] = 'Area 1'; 
$array[1][1]['areaname'] = 'Sub Area 1'; 
$array[1][2]['areaname'] = 'Sub Area 2'; 
$array[1][3]['areaname'] = 'Sub Area 3'; 
$array[2]['areaname'] = 'Area 2'; 
$array[2][1]['areaname'] = 'Sub Area 1'; 

我想显示如下:

<ul> 
    <li> 
     Area 1 
     <ul> 
      <li>Sub Area 1</li> 
      <li>Sub Area 2</li> 
      <li>Sub Area 3</li> 
     </ul> 
    </li> 
    <li> 
     Area 2 
     <ul> 
      <li>Sub Area 1</li> 
     </ul> 
    </li> 
</ul> 

我需要一个代码,其中,因为我想我可以有很多的子区域。例如:

$array[1][1][2][3][4]['areaname']; 

还有另一个条件。该数组获得了其他元素,如$ array [1] ['config'],$ array [1] [2] [3] ['link']或$ array [1] [不应该加入的另一个元素数组循环] ...我只需要打印areaname。

+1

你应该对Google递交一下主题。从长远来看,学习它会为您提供比剪切和粘贴解决方案更好的效果。 – Josh

+0

一直在尝试和阅读,我可以在函数内部递归地打印它,并在循环后调用它,如果$ value是一个数组,但打印HTML时会出现问题。找不到解决方案来关闭UL,或者关闭UL或L1时... – Henrique

回答

3
$array = array(); 
$array[1]['areaname'] = 'Area 1'; 
$array[1][1]['areaname'] = 'Sub Area 1'; 
$array[1][2]['areaname'] = 'Sub Area 2'; 
$array[1][3]['areaname'] = 'Sub Area 3'; 
$array[2]['areaname'] = 'Area 2'; 
$array[2][1]['areaname'] = 'Sub Area 1'; 

function generate_html_list_recursive(&$data, $labelKey) 
{ 
    // begin with an empty html string 
    $html = ''; 

    // loop through all items in this level 
    foreach($data as $key => &$value) 
    { 
     // where only interested in numeric items 
     // as those are the actual children 
     if(!is_numeric($key)) 
     { 
      // otherwise continue 
      continue; 
     } 

     // if no <li> has been created yet, open the <ul> 
     $html .= empty($html) ? '<ul>' : ''; 

     // extract the label from this level's array, designated by $labelKey 
     $label = isset($value[ $labelKey ]) ? $value[ $labelKey ] : ''; 

     // open an <li> and append the label 
     $html .= '<li>' . $label; 

     // call this funcion recursively 
     // with the next level ($value) and label key ($labelKey) 
     // it will figure out again whether that level has numeric children as well 
     // returns a new complete <ul>, if applicable, otherwise an empty string 
     $html .= generate_html_list_recursive($value, $labelKey); 

     // close our currently open <li> 
     $html .= '</li>'; 
    } 

    // if this level has <li>'s, and therefor an opening <ul>, close the <ul> 
    $html .= !empty($html) ? '</ul>' : ''; 

    // return the resulting html 
    return $html; 
} 

echo generate_html_list_recursive($array, 'areaname'); 
+0

谢谢你,工作完美。使用&on $ data的原因是什么,因为有或没有完美的作品。 – Henrique

+0

@Henrique:'&'意味着参数将[通过引用传递](http://php.net/manual/en/language.references.pass.php),从而不会产生不必要的数据副本。这对于对象来说不是必需的,因为那些对象通常会被引用传递。 –

+0

这意味着当传递一个数组时,它只会被复制函数中的引用元素?谢谢, – Henrique