从 While 循环填充 PHP 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6741425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:07:59  来源:igfitidea点击:

Populate PHP Array from While Loop

phpmysqlarraysloopswhile-loop

提问by JosephD

If I am fetching data from a MySQL database and using a while loop to iterate through the data how would I add each one to array?

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

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

}

回答by alex

Build an array up as you iterate with the whileloop.

while循环迭代时构建一个数组。

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

Alternatively, if you used PDO, you could do this automatically.

或者,如果您使用PDO,您可以自动执行此操作

回答by squinlan

This will do the trick:

这将解决问题:

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

回答by Blake

This has been one of the fastest ways for me to create (multi-dimensional) arrays. I'm not sure if you want all of your results smooshed into one array or not.

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

// 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);

You can use print_r($array) to see the results.

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

回答by 2114L3

my fav is the following;

我最喜欢的是以下内容;

$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
}

you dont need to pop the last line, but it does leave a blank if you omit it. works the same for mysql obviously.

您不需要弹出最后一行,但如果您省略它,它确实会留空。显然,对 mysql 的作用是一样的。

回答by M.Nabeel

If you have multiple columns in your Departments table and you want to save in different array.

如果您的 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'];
}