PHP knowledge

Probabilistic lottery (lottery_raffle)
//chance is the probability of drawing, the smaller the value, the smaller the probability
$arr = [
    ['name'=>'1000 yuan mobile phone','chance'=>'1'],
    ['name '=>'100 yuan voucher','chance'=>'10'],
    ['name'=>'10 yuan voucher','chance'=>'100'],
    ['name'=>' Thank you for participating','chance'=>'700'],
];
/**
 * The probability algorithm of the lottery
 * @param array $prizeArr Prize array
 * @param string $index Probability key name
 * @return mixed Prizes drawn
 */
function lottery_raffle($prizeArr,$index='chance')
{
    $result = '';
    $randArr = [];

    $i = 1;
    foreach($prizeArr as $item){
        $randArr[$i] = $item[$index];
        $i++;
    }
    //Total probability precision of probability array
    $proSum = array_sum($randArr);

    //Probability array loop
    foreach ($randArr as $key => $val) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $val) {
            $result = $key;
            break;
        } else {
            $proSum -= $val;
        }
    }
    return $prizeArr[$result];
}

Get the specified file extension (get_file_extension)
/**
 * Get the specified file extension File extension
 * @param array $input input array
 * @param string $columnKey specified array list
 * @param null $indexKey
 * @return array
 */
function get_file_extension($file) {
    //The getExtension method of the SPLFileInfo class requires 5.3.6+ version
    if(version_compare(PHP_VERSION,'5.3.6','>=')){
        $fileInfo = new splFileInfo($file);
        return $fileInfo->getExtension( );
    }else{
        $fileInfo = pathinfo($file);
        return $fileInfo['extension'];
    }
}

$file = 'C:\Users\Administrator\Desktop\New Folder\127.0.0.1\test.txt' ;
//output txt
echo $test->get_file_extension($file);

format file size (file_format_size)
/**
 * format file size
 * @param string $file specified file
 * @param array $unitList corresponding unit list
 * @ return string
 */
function file_format_size($file, $unitList = array()){
    $size = filesize($file);
    if(empty($size)){
        return '';
    }
    if(empty($unitList))
        $unitList = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");


    $i = intval(log($size, 1024));
    return (round($size/pow(1024, $i), 2) . $unitList[$i]);
}


$file = 'test.txt';


//输出 100KB
echo file_format_size($file);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688843&siteId=291194637