【问题标题】:Populate PHP Array from While Loop从 While 循环填充 PHP 数组
【发布时间】:2011-10-08 03:47:55
【问题描述】:

如果我从 MySQL 数据库中获取数据并使用 while 循环遍历数据,我将如何将每个数据添加到数组中?

$result = mysql_query("SELECT * FROM `Departments`");
while($row = mysql_fetch_assoc($result))
{

}

【问题讨论】:

    标签: php mysql arrays loops while-loop


    【解决方案1】:

    在使用while 循环进行迭代时构建一个数组。

    $result = mysql_query("SELECT * FROM `Departments`");
    $results = array();
    while($row = mysql_fetch_assoc($result))
    {
       $results[] = $row;
    }
    

    或者,如果你使用PDO,你可以do this automatically

    【讨论】:

    • 如何在一个数组中只放一列,索引od数组应该是主键?
    • @bhawin 了解 PHP 数组的工作原理,您会发现它很简单
    【解决方案2】:

    这样就可以了:

    $rows = array();
    $result = mysql_query("SELECT * FROM `Departments`");
    while($row = mysql_fetch_assoc($result))
    {
      $rows[] = $row;
    }
    

    【讨论】:

      【解决方案3】:

      这是我创建(多维)数组的最快方法之一。我不确定您是否希望将所有结果都压缩到一个数组中。

      // Read records
      $query = "SELECT * FROM `Departments`"; 
      $query = mysql_query($query);
      
      // Put them in array
      for($i = 0; $array[$i] = mysql_fetch_assoc($query); $i++) ;
      
      // Delete last empty one
      array_pop($array);
      

      您可以使用 print_r($array) 查看结果。

      【讨论】:

        【解决方案4】:

        以下是我的最爱;

        $result=odbc_exec($conn,$sql);
        if ($result) {
            while($found_results[] = odbc_fetch_array($result)) { } 
            array_pop($found_results); //pop off the empty line from while loading
        }
        

        你不需要弹出最后一行,但如果你省略它,它确实会留下空白。 显然,对于 mysql 也一样。

        【讨论】:

          【解决方案5】:

          如果您的 Departments 表中有多个列,并且您想保存在不同的数组中。

          $result = mysql_query("SELECT * FROM `Departments`");
          $dept_id = array();
          $dept_name=array();
          while($row = mysql_fetch_assoc($result))
          {
          //fetches and store all results in id column on your departments table
          $dept_id= $row['id'];
          //fetches and store all results in name column on your departments table    
          $dept_name=$row['name'];
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-05-30
            • 1970-01-01
            • 2015-04-30
            • 1970-01-01
            • 1970-01-01
            • 2016-08-03
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多