thinkphpÔõôËæ»úÅÌÎʼ¸ÌõÊý¾Ý
ÔÚ¿ª·¢webÓ¦ÓóÌÐòÖУ¬¾³£ÐèÒªÅÌÎÊËæ»úÊý¾Ý£¬ÒÔ±ãʵÏÖ²î±ðµÄÓªÒµÂß¼ºÍЧ¹û¡£ÔÚthinkphp¿ò¼ÜÖУ¬¿ÉÒÔʹÓöàÖÖÊÖÒÕºÍÒªÁìʵÏÖËæ»úÅÌÎÊÊý¾ÝµÄ¹¦Ð§¡£
Ò»ÖÖ³£¼ûµÄÒªÁìÊÇʹÓÃmysqlµÄrandomº¯Êý£¨rand()º¯Êý£©¡£Õâ¸öº¯Êý¿ÉÒÔͨ¹ýÖ¸¶¨ÆðµãºÍÖյ㣬ÅÌÎÊÒ»¶¨¹æÄ£ÄÚµÄËæ»úÊý¾Ý¡£ºÃ±ÈÒªÅÌÎÊÒ»ÕÅ$tb_test±íÖÐidÔÚ10µ½100Ö®¼äµÄËæ»úÊý¾Ý£¬¿ÉÒÔʹÓÃÈçϵĴúÂ룺
<?php use think\Db; $data = Db::name('test')->where('id', 'between', [10, 100])->orderRaw('rand()')->limit(10)->select();
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬whereÌõ¼þÖ¸¶¨ÁËidµÄ¹æÄ££¬orderRawº¯ÊýÖ¸¶¨ÁËƾ֤Ëæ»ú˳ÐòÅÅÐò£¬limitº¯ÊýÖ¸¶¨ÁËÅÌÎʵÄÊý¾ÝÌõÊý¡£Õâ¸öÒªÁìµÄÈõµãÊÇЧÂʵÍÏ£¬µ±±íÖÐÊý¾ÝÁ¿½Ï´óʱ£¬ÅÌÎÊËÙÂÊ»áÏÔ×űäÂý¡£
ÁíÒ»ÖÖÒªÁìÊÇʹÓÃPHPµÄrandº¯Êý£¬Í¨¹ý±àдӪҵÂß¼ºÍº¯ÊýʵÏÖËæ»úÅÌÎÊÊý¾ÝµÄ¹¦Ð§¡£Ë¼Ð÷ÈçÏ£º
Ê×ÏÈ£¬´ÓÅÌÎʱíÖлñÈ¡¼Í¼µÄ×ÜÊý£¬Æ¾Ö¤ÒªÇóÅÌÎʵļͼÊý£¬ÅÌËã³öËùÐè¼Í¼µÄidºÅ¡£
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
È»ºó£¬Æ¾Ö¤idºÅÅÌÎÊÊý¾Ý£¬²¢ÇÒ°ü¹ÜÅÌÎʳöÀ´µÄÊý¾ÝÊÇËæ»úµÄ¡£ÆäÖУ¬¿ÉÒÔʹÓÿØÖÆrandº¯ÊýËæ»úÐÔµÄÖÖ×ÓÖµ£¬°ü¹ÜÅÌÎÊЧ¹ûµÄËæ»úÐÔ¡£ÁíÍ⣬ÔÚ´úÂëʵÏÖÀú³ÌÖУ¬Ò»¶¨×¢ÖØʹÓûº´æÊÖÒÕ£¬×èֹƵÈÔÅÌÎÊÊý¾Ý¿â¡£
ÏêϸµÄ´úÂëʵÏÖÈçÏ£º
<?php use think\Cache; use think\Db; //»ñÈ¡Êý¾Ý±í×ܼͼÊý $count = Db::name('test')->count(); //Ö¸¶¨ÅÌÎʼͼÊý $num = 10; //ÌìÉúËæ»úÊýÖÖ×Ó $seed = rand(0, $count - 1); //ÌìÉúidÊý×é $id_arr = range(1, $count); shuffle($id_arr); $id_arr = array_slice($id_arr, 0, $num); //ÅÌÎÊÊý¾Ý $data = Cache::remember('random_data', function() use ($id_arr) { $data = Db::name('test')->where('id', 'in', $id_arr)->select(); return $data; }, 60);
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬rangeº¯ÊýÓÃÓÚÌìÉúÒ»¸öÖ¸¶¨¹æÄ£µÄÊý×飬shuffleº¯ÊýÓÃÓÚ½«Êý×éËæ»ú´òÂÒ£¬array_sliceº¯ÊýÓÃÓÚ½ØÈ¡Êý×éÖ¸¶¨³¤¶ÈµÄ²¿·Ö¡£CacheÀàÓÃÓÚʵÏÖÊý¾Ý»º´æ£¬×èֹƵÈÔÅÌÎÊÊý¾Ý¿â¡£¿ÉÒÔƾ֤ÏÖʵӪҵÐèÇ󣬵÷½â»º´æʱ¼ä»ººÍ´æÕ½ÂÔ¡£
ÒÔÉÏÁ½ÖÖÒªÁ춼¿ÉÒÔʵÏÖËæ»úÅÌÎÊÊý¾ÝµÄ¹¦Ð§£¬ÏêϸʹÓÃÄÄÒ»ÖÖÊÖÒÕҪƾ֤ÏÖʵӪҵ³¡¾°ºÍÐèÇóÀ´È·¶¨¡£ÔÚ¿ª·¢webÓ¦ÓóÌÐòʱ£¬Ó¦Æ¾Ö¤ÐÔÄÜ¡¢Ð§ÂÊ¡¢Çå¾²ÐԵȷ½ÃæµÄ˼Á¿£¬Ñ¡ÔñºÏÊʵÄÊÖÒÕºÍÒªÁ죬ʵÏÖ¹¦Ð§ÓÅ»¯ºÍÌáÉýÓû§ÌåÑé¡£
ÒÔÉϾÍÊÇthinkphpÔõôËæ»úÅÌÎʼ¸ÌõÊý¾ÝµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡