1

任务描述是使用函数:count()、rand() 和 strtoupper() 从我的 PHP 数组中打印出所有大写的随机名称。代码:http: //ideone.com/nwjyoa


<?php
// Create an array and push on the names
$friends=array("Mike", "Ondrej", "Honza", "Danca", "Misa", "Verca");
array_push($friends, "Michal", "Vendulka", "Daniela");
// Sort the list
sort($friends);
// Randomly select a winner!
$winner = array_rand($friends, 1);
echo "<p>$winner</p>";
// Print the winner's name in ALL CAPS
?>

到目前为止,我从数组中选择了一个随机值,但它给了我它的数字(位置),而不是一个名字:/
你能指出我解决这个问题的正确方向吗?

4

7 回答 7

3

如果array_rand返回一个索引,您应该使用该索引到$friends数组中来获取它的值。

$winner = array_rand($friends, 1);
$winner_name = strtoupper($friends[$winner]);
echo "<p>$winner_name</p>";
于 2013-11-06T11:22:49.027 回答
2

如果它返回索引,只需获取数组中给定索引处的值:

$index = array_rand($friends, 1); // or $index = rand() % count($friends);
$winner = $friends[$index];
于 2013-11-06T11:22:29.907 回答
2

获取随机值形式数组的简单方法。

$color_array =["red","green","blue","light_orange"];
$color_array[rand(0,3)]

现在每次你都会从 Array 中得到不同的颜色。

在你的情况下。

 $friends[rand(0,8)]
于 2020-04-12T20:51:39.270 回答
0

你得到一个数组索引。只需执行 $friends[$winner] 即可。

<?php
// Create an array and push on the names
$friends=array("Mike", "Ondrej", "Honza", "Danca", "Misa", "Verca");
array_push($friends, "Michal", "Vendulka", "Daniela");
// Sort the list
sort($friends);
// Randomly select a winner!
$winner = array_rand($friends, 1);
echo "<p>$friends[$winner]</p>";
// Print the winner's name in ALL CAPS
?>
于 2013-11-06T11:22:19.253 回答
0

你需要像下面这样使用

echo $friends[$winner];
于 2013-11-06T11:22:36.907 回答
0

将值 fromarray_rand作为$friends数组的键。

$winner = strtoupper($friends[array_rand($friends, 1)]);
于 2013-11-06T11:24:57.977 回答
-3
<?php
// Create an array and push on the names
// of your closest family and friends
$family_friends=array();

array_push($family_friends, "Marlon");
array_push($family_friends, "Johanna");
array_push($family_friends, "Leonary");
array_push($family_friends, "Sueann");
array_push($family_friends, "Olucho");
array_push($family_friends, "Allyah");
array_push($family_friends, "Reyna");
array_push($family_friends, "Cinil");
array_push($family_friends, "Carl");
array_push($family_friends, "Martain");
array_push($family_friends, "Christell");
array_push($family_friends, "Joy");

// Sort the list
$sorted = sort($family_friends);


$counted = count($family_friends);

print $counted;

// Randomly select a winner!

$win = array_rand($family_friends,1);

// Print the winner's name in ALL CAPS

$winner = strtoupper($win);
print "<p>$family_friends[$winner] </p>"; ?>
于 2017-02-20T14:46:18.143 回答