带权重的随机输出数组中的元素

$orignial_arr= array(
    "一"=>10,
    "二"=>5,
    "三"=>3,
    "四"=>3,
    "五"=>1,
    '六'=>1,
    '七'=>5,
    '八'=>4,
    '九'=>6,
    "十"=>9
);
function getWeightedArray($orignial_arr){


    $func = function($value, $key) {
        return explode(" ",trim(str_repeat($key." ", $value)));
    };

    $map= array_map($func, $orignial_arr, array_keys($orignial_arr));

    $result=array();
    foreach($map as $value){
        $result=array_merge($result,$value);
    }
    return $result;
}
function genRandomString($orignial_arr,$len)
{


    $chars =getWeightedArray($orignial_arr);
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = "";
    for ($i=0; $i<$len; $i++)
    {
        $rand = $chars[mt_rand(0,$charsLen)];
        if(stripos($output,$rand)=== false)
        {
            $output .= $rand;
        }else
        {
            $i--;
        }
    }  
    return $output;
}
$str = genRandomString($orignial_arr,5);
echo $str;

 

 

posted on 2013-09-17 09:39  pinocchioatbeijing  阅读(645)  评论(0编辑  收藏  举报

导航