如何将2个关联数组的内容回显到一个表中?

问题描述 投票:1回答:2

这是我的代码片段,结果不是我想要的东西。我有2个关联数组,想要将它们的内容回显到像html tag之前的一个表中。我可以这样做吗?

    team A:                      team B:
    player_one                   player_five
    player_two                   player_six
    player_three                 player_seven
    player_four                  player_eight



<html>
<head>

<title>Untitled</title>
</head>
<body>
  <table widht='100%' border="1">
    <tr>
        <td>team A</td>
        <td>team B</td>

    </tr>

<?php

$team_a=array("goalkeeper"=>"player_one","defender"=>"player_two","midfielder"=>"player_three","forward"=>"player_four");
$team_b=array("goalkeeper"=>"player_five","defender"=>"player_six","midfielder"=>"player_seven","forward"=>"player_eight");



foreach($team_a as $index1 => $value1 ){

foreach($team_b as $index2 => $value2 )
 echo "
            <tr>
                <td>$value1</td>
                <td>$value2</td>

            </tr>
            ";
            }

?>

</table>
</body>
</html>     
php arrays foreach associative-array
2个回答
1
投票

或者,您可以先组合数组并相应地排列它们,然后打印它们:

<?php

$team_a=array("goalkeeper"=>"player_one","defender"=>"player_two","midfielder"=>"player_three","forward"=>"player_four");
$team_b=array("goalkeeper"=>"player_five","defender"=>"player_six","midfielder"=>"player_seven","forward"=>"player_eight");

$teams = array();
$keys = array_keys($team_a);
foreach ($keys as $key) {
    $teams[$key] = array($team_a[$key], $team_b[$key]);
}
?>
<table widht='100%' border="1">
<tr>
    <td>team A</td>
    <td>team B</td>
</tr>
<?php foreach($teams as $players): ?>
    <tr>
    <?php foreach($players as $player): ?><td><?php echo $player; ?></td><?php endforeach; ?>
    </tr>
<?php endforeach; ?>
</table>

Output

或者,如果您不希望触摸原始数组或使用新数组,则只需相应地循环它们:

<?php

$team_a=array("goalkeeper"=>"player_one","defender"=>"player_two","midfielder"=>"player_three","forward"=>"player_four");
$team_b=array("goalkeeper"=>"player_five","defender"=>"player_six","midfielder"=>"player_seven","forward"=>"player_eight");

?>
<table widht='100%' border="1">
<tr>
    <td>team A</td>
    <td>team B</td>
</tr>
<?php foreach($team_a as $key => $value): ?>
    <tr>
        <td><?php echo $value; ?></td><td><?php echo $team_b[$key]; ?></td>
    </tr>
<?php endforeach; ?>
</table>

2
投票
// drop indexes because you don't use them anyway
$a = array_values($team_a);
$b = array_values($team_b);

// process arrays
max = max(count($a), count($b));
for ($i=0; $i < $max; $i++) {
    echo '
    <tr>
        <td>' . (isset($a[$i] ? $a[$i] : '-')) . '</td>
        <td>' . (isset($b[$i] ? $b[$i] : '-')) . '</td>
    </tr>
    ';
}
© www.soinside.com 2019 - 2024. All rights reserved.