简体   繁体   English

从MySQL在PHP中创建数组

[英]Create array in PHP from mysql

I think that I may be over trying things with little sleep but I am having problems creating arrays from mysql queries. 我认为我可能尝试了很少的睡眠,但是我在从mysql查询创建数组时遇到了问题。 I have a query like so: 我有这样的查询:

$result = mysqli_query($con,"SELECT * FROM vehicles ORDER BY id");
while($row = mysqli_fetch_array($result)) {
    $description = $row['description'];
    $description = strtoupper($description);
    $id = $row['id'];
}

I want it to create an array like so: 我希望它创建一个像这样的数组:

$v[1] = "Myarray1";

I have tried this but it does not work: 我已经尝试过了,但是没有用:

$v[ $row['id']] = $row;

Do I have to query like this: 我是否需要这样查询:

while( $row = mysql_fetch_assoc( $result)){}

and if I do, how I do create the array as I need it? 如果可以的话,如何根据需要创建数组?

Many thanks in advance 提前谢谢了

At no point are you creating an array here. 您绝对不会在此处创建数组。 In your loop you are simply modifying some variables that in the context you posted I cannot reason on. 在您的循环中,您只是在修改一些您无法发布的上下文中的变量。

If all you need, no data filtering whatsoever this will do: 如果需要,则不会进行任何数据筛选:

$list = Array();
while( $row = mysqli_fetch_array($result) ) {
   $list[] = $row;
}

[] basically 'appends' in PHP, it is an ugly mechanism but it works. []基本上在PHP中“附加”,这是一个丑陋的机制,但有效。

If you want to access rows per primary key ( id in your case I think ) then simply replace [] with [$row["id"]] 如果要访问每个主键的行(我认为是id ),则只需将[]替换为[$row["id"]]

I'm not exactly sure of the end result you're looking for. 我不确定您要寻找的最终结果。 But if you want to access the results as $row['column'], where 'column' is a column name in your MySQL database, then you need to use mysql_fetch_assoc. 但是,如果要以$ row ['column']的形式访问结果,其中'column'是MySQL数据库中的列名,则需要使用mysql_fetch_assoc。 I think this example will help: 我认为这个例子会有所帮助:

while (($row = mysqli_fetch_assoc($result))) {
   $v[$row['id']] = $row;
}

$v[1]['description'] is the data in the column description for the record with an id=1 $ v [1] ['description']是ID为1的记录的列说明中的数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM