循环后为什么我的数组是空的?

时间:2016-01-31 08:24:05

标签: php arrays

我试图编写一些代码,从数据库中获取随机价格,直到达到特定数量。我希望它将名称和价格添加到数组中,然后使用$total_items在最后打印它,但它只显示最后一项。怎么了?

$total = 0; 
while ( $total <= $amount ) { 
    $query = "SELECT name, price FROM table ORDER BY RAND() LIMIT 1";
    $run_query = mysql_query($query);

    $total_items = array();

    while($row = mysql_fetch_assoc($run_query)) {
        $total_items[] = $row;
        echo $row['name'] . ' / ' . $row['price'] . "<br>";
        $total = $total + $row['price'];
    }
} 

echo "<br>" . Total Amount: ".$total;

print_r($total_items);

2 个答案:

答案 0 :(得分:2)

变量$total_items在while循环中定义,因此在每个while循环中都会被截断,而$total_items只会保留最后的结果。

尝试将其置于while ( $total <= $amount )

之上

答案 1 :(得分:1)

请在while循环之外定义$total_items。并正确地双引号以打印输出。

$total = 0; $total_items = array();

while ( $total <= $amount ){ 
   $query       = "SELECT name, price FROM table ORDER BY RAND() LIMIT 1";
   $run_query   = mysql_query($query);

   while($row = mysql_fetch_assoc($run_query)) {
      $total_items[] = $row;
      echo $row['name'] . ' / ' . $row['price'] . "<br>";
      $total = $total + $row['price'];
   }
} echo '<pre>';echo "Total Amount: ".$total; print_r($total_items);`