PHP selects the records from the database whose IDs exist in the array and arranges them in the order of the arrays.
For example $arr={"5", "7", 1 "", "10", "3", "8"}, to select a record from the database with an ID value of 5,7,1,10,3,8, and in this order.
------Solution--------------------
SQL Code
SELECT * FROM table WHERE ID in (5,7,1,10,3,8) ORDER by Find_in_set (ID, ' 5,7,1,10,3,8 ');
------Solution--------------------
My test results show that PHP sort speed is better than MySQL sort speed, refresh the NN only 1 times is php slow MySQL, please test it
Date_default_timezone_set (' Asia/shanghai ');?
$link = mysql_connect (' localhost ', ' root ');
mysql_select_db (' Test ');
$timeS 1 = microtime ();
$sql = "SELECT * from ' lean ' WHERE ID in (5,7,1,10,3,8) ORDER by Find_in_set (ID, ' 5,7,1,10,3,8 ')";
for ($i = 1, $i <= 100, $++) {
$result = mysql_query ($sql);
while ($row = Mysql_fetch_array ($result))
{
}
//}
$timeE 1 = microtime ();
echo ' self-processing by the database the start and end time difference is: '. ($timeE 1-$timeS 1). '
';
Release the PHP memory first, lest the previous variables affect the efficiency
Unset ($timeS 1);
Unset ($timeS 2);
Unset ($link); The active database has been automatically set, and the current debugging does not have to pass this, so let's release it.
Unset ($sql);
Unset ($result);
Unset ($row);
//////////////////////
$timeS 2 = Microtime ();
$sql = "SELECT * from ' lean ' WHERE ID in (5,7,1,10,3,8)";
$result = mysql_query ($sql);
$data = Array ();
$i = 0;
while ($row = Mysql_fetch_array ($result))
{
$data [$row [' id ']] = $row;
$i + +;
}
$r = Sortdata ($data, Array (5,7,1,10,3,8));
$timeE 2 = Microtime ();
Echo ' Starting and ending time handled by PHP is: '. ($timeE 2-$timeS 2);
Echo 'Sort results
';
Print_r ($R);
Echo '
';
Sort function
function Sortdata ($arr, er) {
$r = Array ();
$i = 0;
foreach ($arr as $key = = $value) {
$r [er [$i]] = $value;
$i + +;
}
return $r;
}