php-随机给定的数组重量

时间:2013-05-30 08:38:50

标签: php arrays random user-agent

我有这个useragents'数组

$userAgents = array ('Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',        //FF4
                   'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1', //F15
                   'Opera/9.80 (Macintosh; Intel Mac OS X; U; en) Presto/2.2.15 Version/10.00',  //O10
                   'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10', //S5
                   'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)',                        //IE7
                   'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1)' //IE8
                   'Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; Trident/5.0)' //IE9
                  );

我想随机使用不同的用户代理,因此我使用了:

$userAgent = $userAgents[array_rand($userAgents)];

如何进行相同的随机选择,但更重要的是,比方说,3个第一个数组条目......?

2 个答案:

答案 0 :(得分:1)

您可以使用加权结果生成新数组

<?php

$original_array = array(
  // array(weight, string),
  array(1, 'a'),
  array(3, 'b'),
  array(3, 'c'),
  array(2, 'd'),
  array(1, 'e'),
);


$weighted_array = array();

foreach ($original_array as $v) {      
  while ($v[0] > 0) {
    $weighted_array[] = $v[1];    
    $v[0]--;  
  }    
}

然后,您可以将$weighted_arrayarray_rand功能一起使用。

var_dump($weighted_array);

/*
array(10) {
  [0]=>      string(1) "a"
  [1]=>      string(1) "b"
  [2]=>      string(1) "b"
  [3]=>      string(1) "b"
  [4]=>      string(1) "c"
  [5]=>      string(1) "c"
  [6]=>      string(1) "c"
  [7]=>      string(1) "d"
  [8]=>      string(1) "d"
  [9]=>      string(1) "e"
}
*/

答案 1 :(得分:1)

我建议插入一个简单的条件,有机会挑拳3。

$i = rand(0,1); # You can also set more than 1 to get lesser chance.
if($i==1){
    $slice = array_slice($userAgents, 0, 3);
    $userAgent = $userAgents[array_rand($slice)];
}
else
    $userAgent = $userAgents[array_rand($userAgents)];