Php selects records with IDs in the array from the database and arranges them in the order of the array? For example, $ arr ={& quot; 5 & quot;, & quot; 7 & quot;, 1 & quot;, & quot; 10 & quot;, & quot; 3 & quot;, & quot; 8 & quot;}, select records with IDs of, and from the database, in addition, php selects records whose IDs exist in the array from the database and arranges them in the order of the array?
For example, if $ arr = {"5", "7", 1 "", "10", "3", "8"} is selected, the ID value is 5, 7, records of, and are arranged in this order.
------ Solution --------------------
SQL code
SELECT * FROM table WHERE id IN (,) order by FIND_IN_SET (id, '5, 8 ');
------ Solution --------------------
// My test results show that the PHP sorting speed is better than the MySQL sorting speed. if the NN refresh is performed only once, PHP is slower than MySQL. Please test it too.
// Date_default_timezone_set ('Asia/Shanghai ');?
$ Link = mysql_connect ('localhost', 'root ');
Mysql_select_db ('test ');
$ TimeS1 = microtime ();
$ SQL = "SELECT * FROM 'lean 'WHERE id IN (,) ORDER BY FIND_IN_SET (id, '5, 3, 8 ')";
// For ($ I = 1, $ I <= 100, $ ++ ){
$ Result = mysql_query ($ SQL );
While ($ row = mysql_fetch_array ($ result ))
{
}
//}
$ TimeE1 = microtime ();
Echo 'start time and end time difference for self-processing by the database: '. ($ timeE1-$ timeS1 ).'
';
// Release the php memory first, so that the efficiency is not affected by the preceding variables.
Unset ($ timeS1 );
Unset ($ timeS2 );
Unset ($ link); // The active database has been automatically set. you do not need to pass this feature during the current debugging, so release it as well.
Unset ($ SQL );
Unset ($ result );
Unset ($ row );
//////////////////////
$ TimeS2 = microtime ();
$ SQL = "SELECT * FROM 'lean 'WHERE id IN )";
$ Result = mysql_query ($ SQL );
$ Data = array ();
$ I = 0;
While ($ row = mysql_fetch_array ($ result ))
{
$ Data [$ row ['id'] = $ row;
$ I ++;
}
$ R = sortdata ($ data, array ));
$ TimeE2 = microtime ();
Echo 'the start time and end time of PHP processing is: '. ($ timeE2-$ timeS2 );
Echo'Sorting result
';
Print_r ($ r );
Echo'
';
// Sorting function
Function sortdata ($ arr, $ order ){
$ R = array ();
$ I = 0;
Foreach ($ arr as $ key => $ value ){
$ R [$ order [$ I] = $ value;
$ I ++;
}
Return $ r;
}