可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
I wanted to arrange the array of table list with sort() function but i am getting same kind of warning my code as follows :
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
回答1:
The warning is pretty clear: mysql_query
does not return an array with results from the query, but a resource. You need a function like mysql_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()
http://nl3.php.net/mysql_query
And maybe unrelated, but you can sort your results in MySQL right away by adding ORDER BY
to your query.
回答2:
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().
$result = mysql_query("SHOW TABLES FROM `st_db_1`"); $array = array(); while ($row = mysql_fetch_assoc($result)) { $array[] = $row["Tables_in_st_db_1"]; } sort($array); foreach ($array as $item) { echo $item; }
回答3:
I'm not providing the most efficient code imaginable, but this should make it clear what's going on and solve your problem:
$result = mysql_query("SHOW TABLES FROM `st_db_1`"); $my_array_of_table_names = array(); while ( $row = mysql_fetch_array($result, MYSQL_NUM)) { $my_array_of_table_names[] = $row[0]; } sort($my_array_of_table_names); foreach ($my_array_of_table_names as $table_name){ echo "$table_name\n"; }
回答4:
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 call mysql_fetch_array()
or similar. (there are a range of functions available, but that's probably the best one to use in this case). Then sort()
the data from that, not $result
.
回答5:
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.