将 MYSQL 结果放入 PHP 数组

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

Putting MYSQL results into a PHP Array

phpmysqlarrays

提问by Marty

I have an array, using this structure.

我有一个数组,使用这个结构。

$data = array(
array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18)
);

I want to read data from a MYSQL table into this array. Here is my code

我想将 MYSQL 表中的数据读入这个数组。这是我的代码

$sql = "select * from mynames limit 10";
$result = mysql_query($sql);
$data = mysql_fetch_array($result, MYSQL_NUM);

The array is not filling up. Can anybody show me how to fill the array?

数组没有填满。有人可以告诉我如何填充数组吗?

回答by fatnjazzy

    while($data = mysql_fetch_assoc($result)){
        $row[] = $data;
    }
    print_r($row);

回答by brianreavis

Are you looking to append results to $data? If so, you can do something like this:

您是否希望将结果附加到$data? 如果是这样,您可以执行以下操作:

$data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
    array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18)
);

$sql = "SELECT * FROM mynames LIMIT 10";
$result = mysql_query($sql);

while (($row = mysql_fetch_array($result, MYSQL_NUM)) !== false) {
    $data[] = $row;
}

Or, if you're looking to merge the rows you get back from MySQL with the rows in $data, you can do something like:

或者,如果您希望将从 MySQL 返回的行与 中的行合并$data,您可以执行以下操作:

$i = 0;
while (($row = mysql_fetch_array($result, MYSQL_NUM)) !== false) {
    $data[$i] = array_merge($data[$i], $row); 
    $i++;
}

回答by borrible

mysql_fetch_arraywill get the next row from the results, returning falsewhen there are no more rows. To propagate an array with all the results you need to iterate (e.g. with a while ($row = mysql_fetch_array(...).

mysql_fetch_array将从结果中获取下一行,false当没有更多行时返回。要传播具有您需要迭代的所有结果的数组(例如使用 a while ($row = mysql_fetch_array(...)。