数组效果不佳

时间:2015-09-17 10:10:56

标签: php mysql loops for-loop while-loop

我是PHP新手。我有一个代码,其中我使用2个SQL命令。第一个命令获取第一个最新行,第二个命令获取第二个最新行。此代码位于文件sqlquery.php

这里是sqlquery.php

的代码
<?php
include ("connection.php");

我的代码问题是我的数组在所有行中打印相同的记录。但在Db中有不同的记录。我的代码是每行只打印第一条记录

我想输出我的代码就像这样

1 个答案:

答案 0 :(得分:2)

问题是双循环,现在对于第一个查询的每个结果,你为第二个查询的每个结果添加一个数组项有效地复制数组项,你可以改变这个

while($row1 = mysql_fetch_assoc($result1)){
        while($row2 = mysql_fetch_assoc($result2)){

要:

while($row1 = mysql_fetch_assoc($result1) && $row2 = mysql_fetch_assoc($result2))
{

最好更改您的SQL查询,但要将所有值合并到一个请求中。

你能做的另一件事虽然不太好看:

while($row1 = mysql_fetch_assoc($result1))
{        
    $opinion[]= $row1['opinion'];
    $action[]= $row1['atitle'];
    $long_term[]= $row1['ltitle'];
    $outlook[]= $row1['otitle'];
    $rating_type[]= $row1['ttitle'];
    $short_term[]= $row1['stitle'];
}
while($row2 = mysql_fetch_assoc($result2))
{
    $p_long_term[]= $row2['ltitle'];
    $p_short_term[]= $row2['stitle'];
}
相关问题