从mysql查询php创建数组 [英] create array from mysql query php

查看:51
本文介绍了从mysql查询php创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,我不明白.我有一个拥有所有者和类型的数据库(当然还有更多).我想获取所有者等于当前用户的所有类型值的列表,但我只得到两个结果

I have a little problem that I don't understand. I have a db that has an owner and type (and more off course). I want to get a list of all the type values that has owner equal to the current user, but I get only two result

$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ORDER BY id DESC "; 

 $result = mysql_query($sql,$con); 

 print_r(mysql_fetch_array($result));

打印出来:

Array ( [0] => 18 [type] => 18 )

$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' "; 

打印出来:

Array ( [0] => 16 [type] => 16 ) 

结果应该是数组中的 19、19、18、17、16.这就是将我设置为所有者的所有类型.

And the result should be something like 19, 19, 18, 17, 16 in an array. Thats all the types that has me as set as owner.

我现在已经开始工作了:

I have got this working now:

for ($x = 0; $x < mysql_num_rows($result); $x++){
 $row = mysql_fetch_assoc($result);  
 echo $row['type']; 
}

这里我正确打印了所有值,但我需要创建一个包含所有值的数组.我虽然可以使用array_push,但大多数都有更好的方法.我以为我会通过一个简单的 mysql 查询获得所有类型值.

Here I print out all the values correctly, but I need to create an array with all the values. I though I could use array_push, but there most be a better way of doing it. I thought I would get all the type values with a simple mysql query.

推荐答案

这通常是在 while 循环中完成的:

Very often this is done in a while loop:

$types = array();

while(($row =  mysql_fetch_assoc($result))) {
    $types[] = $row['type'];
}

查看文档中的示例.

mysql_fetch_* 方法将始终获取结果集的 next 元素:

The mysql_fetch_* methods will always get the next element of the result set:

返回与获取的行对应的字符串数组,如果没有更多行,则返回 FALSE.

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

这就是 while 循环起作用的原因.如果不再有任何行 $row 将是 false 并且 while 循环存在.

That is why the while loops works. If there aren't any rows anymore $row will be false and the while loop exists.

似乎mysql_fetch_array 得到不止一行,因为默认情况下它得到的结果为正常作为关联值:

It only seems that mysql_fetch_array gets more than one row, because by default it gets the result as normal and as associative value:

通过使用 MYSQL_BOTH(默认),您将获得一个包含关联索引和数字索引的数组.

By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.

你的例子最能说明问题,你得到相同的值 18 并且你可以通过 $v[0]$v['type' 访问它].

Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'].

这篇关于从mysql查询php创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆