如何使用键作为指标?

时间:2014-10-04 05:04:29

标签: php html arrays

正在探索数组以及如何使用它

我遇到了这个不寻常的阵列。

我正在尝试使用我在下面发布的数组来实现此输出。

如何完成此操作?

<table>
   <tr>
      <th>DOGS</th>
      <th>CATS</th>
      <th>BIRDS</th>
   </tr>
   <tr>
      <td><?php echo $dogs;?></td>
      <td><?php echo $cats;?></td>
      <td><?php echo $birds;?></td>
   </tr>
</table>

Array
(
    [cats] => Array
        (
            [0] => persian
            [1] => ragdoll
            [2] => siberian
            [3] => savannah
        )

    [dogs] => Array
        (
            [0] => husky
            [1] => bulldog
            [2] => beagle
            [3] => labrador
        )

    [birds] => Array
        (
            [0] => parrot
            [1] => owl
            [2] => eagle
            [3] => love birds
        )
)

这是我真正需要的输出:

DOGS       CATS       BIRDS
husky      persian    parrot
bulldog    ragdoll    owl
beagle     siberian   eagle
labrador   savannah   love birds

1 个答案:

答案 0 :(得分:4)

你需要先循环它们,你不能直接回显数组:

$animals = array(
    'dogs' => array('husky', 'bulldog', 'beagle', 'labrador'),
    'cats' => array('persian', 'ragdoll', 'siberian', 'savannah'),
    'birds' => array('parrot', 'owl', 'eagle', 'love birds'),
);

?>

<table cellpadding="10">
<tr><th>DOGS</th><th>CATS</th><th>BIRDS</th></tr>
<?php
$types = array_keys($animals);
for($i = 0; $i < count($animals['cats']); $i++) {
    echo '<tr>';
    foreach($types as $type) {
        echo '<td>' . $animals[$type][$i] . '</td>';
    }
    echo '</tr>';
}
?>
</table>

Sample Output