search
HomeBackend DevelopmentPHP TutorialPHP realizes the turntable lottery algorithm sharing php examples

This article mainly introduces the algorithm of realizing the big carousel lottery in PHP in detail. It has certain reference value. Interested friends can refer to it.

The example of this article is to share with you the implementation of the carousel lottery in PHP. The specific code of the algorithm is for your reference. The specific content is as follows

Process:

1. Assemble the award array

2. Calculate the probability

3. Return the winning situation

The code is as follows:

The winning probability ' v ' can be set in the background and passed to this method, NoteTransfer integer

function get_gift(){ 
    //拼装奖项数组 
    // 奖项id,奖品,概率
    $prize_arr = array(  
     '0' => array('id'=>1,'prize'=>'平板电脑','v'=>0),  
     '1' => array('id'=>2,'prize'=>'数码相机','v'=>0),  
     '2' => array('id'=>3,'prize'=>'音箱设备','v'=>0),  
     '3' => array('id'=>4,'prize'=>'4G优盘','v'=>5),  
     '4' => array('id'=>5,'prize'=>'10Q币','v'=>0),  
     '5' => array('id'=>6,'prize'=>'空奖','v'=>5),  
    );  
    foreach ($prize_arr as $key => $val) {  
     $arr[$val['id']] = $val['v'];//概率数组  
    }  
    $rid = $this->get_rand($arr); //根据概率获取奖项id  
    $res['yes'] = $prize_arr[$rid-1]['prize']; //中奖项  
    unset($prize_arr[$rid-1]); //将中奖项从数组中剔除,剩下未中奖项  
    shuffle($prize_arr); //打乱数组顺序  
    for($i=0;$i<count($prize_arr);$i++){  
     $pr[] = $prize_arr[$i][&#39;prize&#39;]; //未中奖项数组 
    }  
    $res[&#39;no&#39;] = $pr; 
    // var_dump($res);

     
    if($res[&#39;yes&#39;]!=&#39;空奖&#39;){ 
      $result[&#39;status&#39;]=1; 
      $result[&#39;name&#39;]=$res[&#39;yes&#39;]; 
    }else{ 
      $result[&#39;status&#39;]=-1; 
      $result[&#39;msg&#39;]=$res[&#39;yes&#39;]; 
    }  
    //return $result; 
    var_dump($result);
  } 

  //计算中奖概率
  function get_rand($proArr) {  
   $result = &#39;&#39;;  
   //概率数组的总概率精度  
   $proSum = array_sum($proArr);  
   // var_dump($proSum);
   //概率数组循环  
   foreach ($proArr as $key => $proCur) {  
    $randNum = mt_rand(1, $proSum); //返回随机整数 

    if ($randNum <= $proCur) {  
     $result = $key;  
     break;  
    } else {  
     $proSum -= $proCur;  
    }  
   }  
   unset ($proArr);  
   return $result;  
  }

Rendering:

The above is the entire content of this article , I hope it will be helpful to everyone’s study, and I also hope everyone will support the php Chinese website.

Articles you may be interested in:

PHP uses curl_multi to implement concurrent requests Example PHP tips

PHP performance testing tool xhprof installation and use method detailed php skills

PHP implements the method of locating the cause of the fault through strace php skills

The above is the detailed content of PHP realizes the turntable lottery algorithm sharing php examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools