如何将2个关联数组的内容回显到一个表中?
问题描述:
this is my code snippets and the result is not the thing that i want.I have 2 associative arrays and want to echo their contents into one table like before the html tag.how can i do that?
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>
答
Alternatively, you could combine the arrays first and line them up accordingly, them print them:
<?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>
Or if you do not want the original arrays touched or using a new array, then just loop them accordingly:
<?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>
答
// 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>
';
}