PHP行走和打印多维数组

时间:2011-09-28 01:29:46

标签: php arrays multidimensional-array arraylist

任何人都可以帮我处理一些编码吗?

我得到了以下数组配置:

$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] [另一个不应该进入的元素数组循环] ...我只需要打印海棠。

2 个答案:

答案 0 :(得分: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' );

答案 1 :(得分:0)