我的php代码抛出值,但将两个数组数据混合在一起。如何修复代码来整理它!提前感谢!
here $Array1=Array ([0] => Array ([0] => Abdul Razak, Ahmed Deedat [name] => Abdul Razak, Ahmed Deedat [1] => 11 [standard] => 11 [2] => 12/08/16 [date] => 12/08/16))$ Array2 =数组([0]=>数组([0]=>雀跃起来,拉吉拉蒂[名字]=>,raj[1] => 12[标准]=> 12[2]=> 12/08/16[日期]=> 12/08/16))
上面的数组只是不完整的样本,行数超过10我想要这样的输出:
left wing | right wing
array 1, key [0] values | array 2 [0] key values
array1, key [1] values | array 2 [1] key values
and so on till both arrays doesn't end
代码是这样的:
<?php
<table id="fire">
<caption><?php echo "Achievements by the selected two are:";?> </caption>
<tr>
<th>Wing 1</th>
<th>Wing 2</th>
</tr>
<tr>
<?php
if(isset($raws1)) {
foreach($raws1 as $raw1){ ?>
<tr>
<?php
if($raw1==null){
echo "<td>---</td>";
} else {
echo "<td>". $raw1['name'] . ", " . $raw1['standard'] .", on ".$raw1['dated']." , ".$raw1['achieved'].", at ".$raw1['at']. ", ".$raw1['on'].", (". $raw1['position'] ."</td>";
}
if(isset($raws2)) {
foreach($raws2 as $raw2){ ?>
<tr>
<?php
if($raw2==null){
echo "<td>---</td>";
} else {
echo "<td>". $raw2['name'] . ", " . $raw2['standard'] .", on ".$raw2['dated']." , ".$raw2['achieved'].", at ".$raw2['at']. ", ".$raw2['on'].", (". $raw2['position'] ."</td></tr>";
} }}}}?>
</table>
?>
用标题输出表的开始部分看起来已经很好了。
<table id="fire">
<caption><?php echo "Achievements by the selected two are:";?> </caption>
<tr>
<th>Wing 1</th>
<th>Wing 2</th>
</tr>
<?php
这是执行PHP部分的一种方法。把两个数组放到一个数组中。这将有助于防止以后的重复代码,因为您可以通过外部数组的foreach
对两个内部数组执行相同的操作。
$both = [$raw1, $raw2];
获取两个数组的最大计数。
$count = max(array_map('count', $both));
然后可以使用for
循环循环到最大计数。
for ($i=0; $i < $count; $i++) {
echo '<tr>';
// This foreach loop will loop over the two arrays ($raw1 and $raw2)
foreach ($both as $array) {
// check the $i element of both the arrays and output its value if it's set
if (empty($array[$i])) {
echo "<td>---</td>";
} else {
$x = $array[$i];
echo "<td>$x[name], $x[standard], etc. ...";
}
}
echo '</tr>';
} ?>
</table>
我只在里面创建了两个新表,它简化了很多东西。
仍然可以只在一个表中执行此操作。但我认为这不是你的要求。
试试。
<table id="fire">
<caption><?php echo "Achievements by the selected two are:";?> </caption>
<tr>
<th>Students 1</th>
<th>student 2</th>
</tr>
<tr>
<td>
<?php
if(isset($raws1)) {
?><table><?php
foreach($raws1 as $raw1)
{ ?>
<tr>
<?php
if($raw1==null){
echo "<td>---</td>";
} else {
echo "<td>". $raw1['name'] . ", " . $raw1['standard'] .", on ".$raw1['dated']." , ".$raw1['achieved'].", at ".$raw1['at']. ", ".$raw1['on'].", (". $raw1['position'] ."</td>";
}
?></tr><?php
}
?></table><?php
}
?></td><td><?php
if(isset($raws2)) {
?>
<table>
<?php
foreach($raws2 as $raw2){
?>
<tr>
<?php
if($raw2==null){
echo "<td>---</td>";
} else {
echo "<td>". $raw2['name'] . ", " . $raw2['standard'] .", on ".$raw2['dated']." , ".$raw2['achieved'].", at ".$raw2['at']. ", ".$raw2['on'].", (". $raw2['position'] ."</td></tr>";
}
?></tr><?php
}
?></table><?php
}?>
</td>
</table>
如果键相同,只需对所有键执行foreach循环以获取所需的数据。
foreach($array1 as $key=>$value)
{
echo "<td>{$array1[$key]}</td><td>{$array2[$key]}</td>"
}