如何将2个关联数组的内容回显到一个表中?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将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
$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>
或者,如果您不希望触摸原始数组或使用新数组,则只需相应地循环它们:
<?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>
';
}
以上是关于如何将2个关联数组的内容回显到一个表中?的主要内容,如果未能解决你的问题,请参考以下文章