PHP:警告:sort() 期望参数 1 为数组,给定资源
我想用 sort() 函数排列表列表数组,但我收到了同样类型的警告。
<?php
require_once("lib/connection.php");
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
sort($result);
foreach ($result as $result){
echo $result ;
}
?>
我收到的警告是:
警告:sort() 期望参数 1 为数组,资源在第 9 行 st_db_1\test_2.php 的 C:\wamp\www\Copy (4) 中给出 警告:为 C:\wamp\www\Copy (4) of st_db_1\test_2.php 第 10 行的 foreach() 提供的参数无效
I wanted to arrange the array of table list with sort() function but i am getting same kind of warning.
<?php
require_once("lib/connection.php");
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
sort($result);
foreach ($result as $result){
echo $result ;
}
?>
and the warning I am getting are:
Warning: sort() expects parameter 1 to be array, resource given in C:\wamp\www\Copy (4) of st_db_1\test_2.php on line 9
Warning: Invalid argument supplied for foreach() in C:\wamp\www\Copy (4) of st_db_1\test_2.php on line 10
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
警告非常清楚:
mysql_query
不返回包含查询结果的数组,而是返回资源。您需要像mysql_fetch_array()
这样的函数来返回所需的数据(并且可以对其执行排序操作)。mysql_query()的使用参见手册https://www.php.net /mysql_query
也许不相关,但您可以通过在查询中添加
ORDER BY
立即对 MySQL 中的结果进行排序。The warning is pretty clear:
mysql_query
does not return an array with results from the query, but a resource. You need a function likemysql_fetch_array()
to return the data you need (and on which you can perform a sort operation).See the manual for the use of
mysql_query()
https://www.php.net/mysql_queryAnd maybe unrelated, but you can sort your results in MySQL right away by adding
ORDER BY <fieldname>
to your query.变量 $result 只是结果类型的资源。您需要使用例如 mysql_fetch_assoc( )。
The variable $result is only a resource of the type result. You need to fetch then the data from the result set with e.g. mysql_fetch_assoc().
我没有提供可以想象到的最有效的代码,但这应该可以清楚地说明发生了什么并解决您的问题:
I'm not providing the most efficient code imaginable, but this should make it clear what's going on and solve your problem:
您的问题是您实际上并未从查询中获取数据。
mysql_query()
不会为您提供记录集。它的作用是查询数据库并返回数据库资源,然后您可以使用该资源来获取数据。
您需要的是在调用
mysql_query()
之后,您还需要调用mysql_fetch_array()
或类似的。 (有一系列可用的功能,但这可能是在这种情况下使用的最好的一个)。然后sort()
从中获取数据,而不是$result
。Your problem is that you aren't actually getting the data from the query.
mysql_query()
doesn't give you a recordset.What it does is query the database and returns a database resource which you can then use to get the data.
What you need is after calling
mysql_query()
, you then need to also callmysql_fetch_array()
or similar. (there are a range of functions available, but that's probably the best one to use in this case). Thensort()
the data from that, not$result
.它清楚地表明:它需要一个数组,而你传递的是其他东西。
如果您检查了
$result
的类型,您会发现它不是一个数组,而是一个资源。It clearly says: it expects an array and you pass something else.
If you had checked the type of
$result
you would have seen that it is not an array, intead a resource.