我有一系列'参赛者',可以这样展示:
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3),
...
)
从这些条目中我需要创建另一个名为$draw
的数组。
$draw
数组的username
重复次数与对应的number_of_entries
相同。因此,对于上面的示例,它可能如下所示:
$draw = array("122", "123", "123", "123", "123", "124", "124", "124")
我想要这样我以后可以生成一个随机数,并通过$draw[$randomNumber];
但是,我无法理解如何从$draw
数组创建$all_entrants
数组......我们将非常感谢您的帮助!
答案 0 :(得分:5)
我认为你正在寻找这样的东西?
$draw = array();
foreach($all_entrants as $entrant) // loop through array with entrants
for ($i = 0; $i<$entrant['number_of_entries']; $i++) //get number of entries
$draw[] = $entrant['username']; //add them to the $draw array
答案 1 :(得分:2)
我认为这是一个关于从一组具有不同重量的名称中选择一个的问题。 也许像这样的数组
$group = array(
array('122' => 1),
array('123'=> 4),
array('124'=> 3)
);
首先计算重量的总和,或者可能已经知道了
$total_weight = 0;
foreach($group as $weight){
$total_weight += $weight;
}
然后生成一个从0到$ total_weight的随机数,例如。 0℃; = $ rand_number
$current_total = 0;
foreach($group as $name => $weight){
if($rand_number <= $current_total)
return $name;
$current_total += $weight;
}
-
顺便说一句,我是新来的,更多要学习:)答案 2 :(得分:1)
<?php
$draw = array();
foreach($all_entrants as $entrant) {
for($i=0; $i<$entrant['number_of_entries']; $i++) {
$draw[] = $entrant['username'];
}
}
答案 3 :(得分:1)
$draw = array();
foreach($all_entrants as $entrant) {
for($i=0; $i<$entrant['number_of_entries']; $i++) {
$draw[] = $entrant['username'];
}
}
答案 4 :(得分:1)
检查一下: -
$result=array();
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3)
);
foreach($all_entrants as $value)
for($i=0;$i<$value['number_of_entries'];$i++)
array_push($result,$value['username']);
echo '<pre>';
print_r($result);
输出: -
Array
(
[0] => 122
[1] => 123
[2] => 123
[3] => 123
[4] => 123
[5] => 124
[6] => 124
[7] => 124
)
答案 5 :(得分:1)
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3),
);
$draw = array();
foreach($all_entrants as $entrant) {
$draw = array_merge(
$draw,
array_fill(0, $entrant['number_of_entries'], $entrant['username'])
);
}
var_dump($draw);
答案 6 :(得分:0)
试试这个
$newarray=array();
foreach($all_entrants as $list){
for($i=1;$i<=$list['number_of_entries'];$i++){
array_push($newarray,$list['username']);
}
}
答案 7 :(得分:0)
<?php
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3)
);
$draw = array();
for ($i = 0; $i < count($all_entrants); $i++)
{
$entrants = $all_entrants[$i];
$name = $entrants["username"];
$entry_count = $entrants["number_of_entries"];
for ($j = 0; $j < $entry_count; $j++) $draw[] = $name;
}
print_r($draw);
?>
希望它有所帮助。