php 将来自 SQL 的数据存储在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6034575/
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-25 23:10:19  来源:igfitidea点击:

Storing data from SQL in array

phpsqlarrays

提问by Jason

I am trying to store the data from my sql database into an array. Currently I have this:

我正在尝试将我的 sql 数据库中的数据存储到一个数组中。目前我有这个:

$query = mysql_query("SELECT * FROM  `InspEmail` WHERE  `Company` LIKE  '$company'");

while($row = mysql_fetch_array($query))
    {

        $inspector = $row['name'];

    }

The problem is that I have 8 rows of data. I need to store each 8 names from that database into an array. When I try this:

问题是我有 8 行数据。我需要将该数据库中的每 8 个名称存储到一个数组中。当我尝试这个时:

$inspector = array($row['name']);

It doesn't work.

它不起作用。

回答by andrewmitchell

If you want to store all of the names in an array, you need to define the array outside the scope of the while loop and append to it. Like this:

如果要将所有名称存储在一个数组中,则需要在 while 循环范围之外定义该数组并附加到该数组中。像这样:

$nameArray = array();
while($row = mysql_fetch_array($query)) {
    // Append to the array
    $nameArray[] = $row['name'];   
}

回答by fafnirbcrow

What you want is:

你想要的是:

$inspector[] = $row['name'];

This will store all 8 names in an array similar to:

这会将所有 8 个名称存储在类似于以下内容的数组中:

array(
     [0] => name1
     [1] => name2
     [2] => name3

)

回答by dkretz

Lots of good answers. But if you do this often, you might want to write a little function:

很多好的答案。但是如果你经常这样做,你可能想写一个小函数:

mysql_field_array($sql, $fieldname)
{
    $res = mysql_query($sql);
    $a = array();
    while($row = mysql_fetch_array($res))
    {
        $a[] = $row[$fieldname];
    }
    mysql_free_result($res);
    return $a;
}

回答by Jimesh Gajera

$query = mysql_query("SELECT * FROM  `InspEmail` WHERE  `Company` LIKE  '$company'");
$data = array();
while($row = mysql_fetch_array($query))
{
    $inspector[] = $row;
}
for($i=0;$i<mysql_num_rows($row);$i++)
{
  $data = $inspector[$i];
}
return $data;

Check it...

核实...

回答by Jeroen

Replace this line...

替换这一行...

$inspector = $row['name'];

...with this:

...有了这个:

$inspector [] = $row['name'];

After that, the inspector array contains all the names.

之后,检查器数组包含所有名称。