多个查询数据到单个html表(PHP,Mysql)数组中的位置不正确


Multiple query data into single html table (PHP, Mysql) array not printing in correct position?

我从这个网站得到了代码片段,我使用了它,如下所示

    $data = array();
while($row = mysql_fetch_assoc($num1)) {$data['row'][] = $row;}
while($row = mysql_fetch_assoc($num2))  {$data['row2'][] = $row;}

$count = count($data['row']);
echo "<table>" ;
echo "<tr>";
echo "<td width='300' bgcolor='#99CCF5' align='Left' style='padding-left:30px'><b>Country</b></td>" ;
echo "<td width='150' bgcolor='#99CCF5' align='center'><b>Mid Estimate 1</b></td>";
echo "<td width='150' bgcolor='#99CCF5' align='center'><b>Mid Estimate 2</b></td>";
echo "</tr>";
for($i=0;$i<=$count;$i++)
{
        if(($i % 2) == 1)
        {
            echo "<tr>" ;
            echo "<td align='center'>" . $data['row'][$i]['Country']."</td>";
            echo "<td align='center'>" . $data['row'][$i]['MidEstimate']."</td>";
            echo "<td align='center'>" . $data['row2'][$i]['MidEstimate']."</td>";
            echo "</tr>" ;
        }else
        {
            echo "<tr>" ;
            echo "<td align='center'>" . $data['row'][$i]['Country'] ."</td>";
            echo "<td align='center'>" . $data['row'][$i]['MidEstimate']."</td>";
            echo "<td align='center'>" . $data['row2'][$i]['MidEstimate']."</td>";
            echo "</tr>" ;
        }
}
echo "</table>" ;

这给出了低于的重复使用

图像1http://img4.pixa.us/8ba/19338641.jpg

正确的结果应该像这个

图像2http://img4.pixa.us/c1d/19338642.jpg

也就是说,如果一列中的任何值为空,则下一个附加值将获得该位置。我该如何更正?也就是说,如果任何值为空,那么该列必须为空。

请提前提供帮助并表示感谢。

您必须收集每个国家的数据。由于数组的键不同步,您在问题中的方法会使列表混乱。让我们按"国家"同步您的行:

$data = array();
while($row = mysql_fetch_assoc($num1))
{
    $c = $row['Country'];
    if (!isset($data[$c]))
    {
        $data[$c] = array('Country' => $c);
    }
    $data[$c]['MidEstimate1'] = $row['MidEstimate'];
}
while($row = mysql_fetch_assoc($num2))
{
    $c = $row['Country'];
    if (!isset($data[$c]))
    {
        $data[$c] = array('Country' => $c);
    }
    $data[$c]['MidEstimate2'] = $row['MidEstimate'];
}

现在,您的数组中每个国家都有一行,其中包含来自每个查询的数据。

$i = 0;
foreach ($data as $row)
{
    echo ($i % 2) ? "<tr class='odd'>" : "<tr class='even'>" ;
    echo "<td align='center'>" . $row['Country']."</td>";
    echo "<td align='center'>" . $row['MidEstimate1']."</td>";
    echo "<td align='center'>" . $row['MidEstimate2']."</td>";
    echo "</tr>" ;
}

注意:这只适用于两个SQL查询中都存在"Country"字段。