虽然foreach循环内部的循环没有进入foreach循环

时间:2016-05-27 14:37:42

标签: php mysql

我使用while循环和array_push将日期从query存储到数组。

$h = array();
$j = array();

while ($g = mysql_fetch_array($f)) {
   $date = new DateTime($g['selected_date']);
   echo "<th>" . date_format($date, 'd') . "</th>";
   array_push($h, $date);
   array_push($j, $g['selected_date']);
}

我认为打印那个数组会回到这个状态。

Array (
   [0] => 2016-05-23
   [1] => 2016-05-24
   [2] => 2016-05-25
   [3] => 2016-05-26
   [4] => 2016-05-27
   [5] => 2016-05-28
)

我尝试这样使用:

$a = mysql_query("select * from center") or die(mysql_error());
$arr = array();

foreach($j as $k) {
    while ($b = mysql_fetch_array($a)) {
        $l = "select sum(yid.center_inventory) as 'total' 
              from yl_inventory_details as yid
              left join yl_inventory as yi 
                  on yi.yl_inventory_no = yid.yl_inventory_no
              where yid.center_no = '$b[center_no]'
              and yi.date = '$k'";
        $c = mysql_query("$l") or die(mysql_error());
        $d = mysql_fetch_array($c);
        echo "<tr><td>".$b['center']."</td><td>".$d['total']."</td></tr>";              
    }
}

但它只取第一个值2016-05-23。 while循环似乎没有进入下一个foreach值。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

当您使用mysql_fetch_array时,它会转移到结果中的下一行。到达最后一个结果后,它会开始返回FALSE

要使代码正常工作,您所要做的就是以相反的方式交换循环。

E.g。

$a = mysql_query("select * from center") or die(mysql_error());
$arr = array();
while ($b = mysql_fetch_array($a))
{
    foreach($j as $k)
    {
            $l = "select
                    sum(yid.center_inventory) as total 
                from yl_inventory_details as yid
                left join yl_inventory as yi on yi.yl_inventory_no = yid.yl_inventory_no
                where yid.center_no = {$b['center_no']} and yi.date = {$k}";
            $c = mysql_query($l) or die(mysql_error());
            $d = mysql_fetch_array($c);
            echo
            "<tr>
                <td>{$b['center']}</td>
                <td>{$d['total']}</td>
            </tr>";             
    }
}