开发者

PHP walking and print multi dimensional array

anyone can help me with some coding here?

I got the following array config:

$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';

I want display the following:

<ul开发者_StackOverflow中文版>
    <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>

I need a code where I can have as many sub area as I want. Example:

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

There are also another condition. The array got other elements such as $array[1]['config'], $array[1][2][3]['link'] or $array[1][another array of elements that should not be into the loop] ... I only need print the areaname.


$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' );


You can try to use array_walk() or array_walk_recursive().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜