我有以下PHP多维数组,我想尝试选择4个随机项,然后用标题,图像和文本显示它们。使用我使用的代码,我似乎得到一个随机的数字,而不是我需要的。
<?php
$arr = array(
array(
"image" => "",
"title" => "Open 7 days.",
"text" => "We’re open 7 days a week."
),
array(
"image" => "",
"title" => "Well done",
"text" => "Well done you done great."
),
array(
"image" => "",
"title" => "Rice",
"text" => "Various flavours"
),
array(
"image" => "",
"title" => "Rooms",
"text" => "Roomy rooms for a roomyful time"
),
array(
"image" => "",
"title" => "Keep in touch.",
"text" => "Stay in touchwith us as we'll miss you"
),
array(
"image" => "",
"title" => "Location",
"text" => "We'll show you where we are."
),
array(
"image" => "",
"title" => "The Home",
"text" => "See our home page"
)
);
print_r(array_rand($arr));
答案 0 :(得分:1)
如果您只选择一个条目,array_rand()
将返回一个随机条目的单个密钥。如果您使用num
指定应选择的密钥数,则它会返回num
个随机条目的密钥数。
该函数仅返回随机条目的键,而不返回数组块本身。您必须从返回的键手动构建数组:
// get the random keys
$keys = array_rand($arr, 4);
// initialize result array
$result = array();
// loop through the keys and build the array
foreach ($keys as $k) {
$result[] = $arr[$k];
}
print_r($result);
<强>更新强>
从快速基准测试来看,似乎array_rand()
比使用shuffle()
更大的数组要快得多。基准测试是在具有14336
个元素的数组上完成的,每个元素都有10000
次迭代。
在我的开发机器上获得的结果如下:
14336
10000
array_rand()
版本耗时4.659秒shuffle()
版本耗时15.071秒用于基准测试的代码可以在this gist中找到。
答案 1 :(得分:1)
shuffle()
和array_slice()
完成了这项工作。只需shuffle
您的数组,以便重新排列条目,现在使用4
选择第一个array_slice
项。
shuffle($arr);
print_r(array_slice($arr,0,4));
答案 2 :(得分:0)
了解$num
参数array_rand()
print_r(array_rand($arr, 4));
显示全部:
foreach(array_rand($arr, 4) as $key) {
echo $arr[$key]['text'] ."\n";
//etc
}