将多级关联数组显示为表

时间:2012-12-15 23:54:54

标签: php html arrays

以下是我想要显示的数组示例:

Array
(
    [Media] => Array
    (
        [2012-12-10] => Array
        (
            [Mentor] => Evan Tobin
            [Veteran Member] => James
        )

        [2012-12-21] => Array
        (
            [Mentor] => Evan Tobin
        )
    )
    [Website] => Array
    (
        [2012-12-10] => Array
        (
            [Mentor] => Evan Tobin
        )

        [2012-12-21] => Array
        (
            [Mentor] => Evan Tobin
        )
    )
)

因为你可以看到它有多个团队,每个团队都有多个他们遇到的日期,每天都有不同的人有不同的工作。使用此表我希望它显示为:

Media Team
Role           || 2012-12-10 || 2012-12-21
Mentor         || Evan Tobin || Evan Tobin
Veteran Member ||   James    || 

我已经尝试过使用foreach语句,但只要我进一步了解它就会变得过多。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

你在这里:

<?php
// [your array]
$tabledata = array(
    'Media' => array(
        '2012-12-10' => array(
            'Mentor' => 'Evan Tobin',
            'Veteran Member' => 'James'
        ),
        '2012-12-21' => array(
            'Mentor' => 'Evan Tobin'
        )
    ),
    'Website' => array(
        '2012-12-10' => array(
            'Mentor' => 'Evan Tobin'
        ),
        '2012-12-21' => array(
            'Mentor' => 'Evan Tobin'
        )
    )
);
// [/your array]

// [the tables]
echo '<table border="1">';
foreach($tabledata as $teamkey => $teamval){
    // [helper]
    $dates = array();
    $roles = array();
    foreach($teamval as $datekey => $dateval) {
        if (!in_array($datekey, $dates)) {
            $dates[] = $datekey;
        }
        foreach($dateval as $rolekey=>$roleval) {
            if (!in_array($rolekey, $roles)) {
                $roles[] = $rolekey;
            }
        }
    }
    // [/helper]

    // [team name] >> row 1
    echo '<tr>';
    echo '<th align="left" colspan="'.(sizeof($dates)+1).'">'.$teamkey.' Team</th>';
    echo '</tr>';
    // [/team name]

    // [role column and date column] >> row 2
    echo '<tr>';
    echo '<td>Role</td>';
    foreach($dates as $date) {
        echo '<td>'.$date.'</td>';
    }
    echo '</tr>';
    // [/role column and date column]

    // [role and team member for each date] >> row 3, 4, 5, ... n
    foreach($roles as $role) {
        echo '<tr>';
        echo '<td>'.$role.'</td>';
        foreach($dates as $date) {
            echo '<td>';
            if (isset($teamval[$date][$role])) {
                echo $teamval[$date][$role]; // team member name
            }
            else {
                echo '&nbsp;'; // insert blank space for cross browser support
            }
            echo '</td>';
        }
        echo '</tr>';
    }
    // [/role and team member for each date]
}
echo '</table>';
// [/the tables]

如果您希望每个团队都有单独的表格,您可以将其放入循环中。

希望这有帮助。