我想在第一页上显示从 dati.txt 文件中随机选择的链接(从大约 1000 个链接中随机选择的 5 个链接):
<?php
$righe_msg = file("dati.txt");
$numero=0;
foreach($righe_msg as $riga)
{
$dato = explode("|", trim($riga));
if (trim($dato[5])=="yes")
{
$numero++;
echo"<tr><td bgcolor='#EEEEEE'>» <a href='$dato[2]'> $dato[1]</a></td></tr> ";
}
}
?>
关于达蒂.txt达蒂.txt是这样做的
date1.. |title1..|link1...|description1|email1|yes
date2.. |title2..|link2...|description2|email2|yes
date3.. |title3..|link3...|description3|email3|yes
date4.. |title4..|link4...|description4|email4|yes
date5.. |title5..|link5...|description5|email5|yes
date6.. |title6..|link6...|description6|email6|yes
..
但是,例如,您如何使用此代码获取(链接):
$links = file("dati.txt");
$numLinks = count($links);
$tmp = array();
for ($i = 0; $i < min(5, $numLinks); $i++)
{
$randomIndex = rand(0, $numLinks - 1);
$randomLink = $links[$randomIndex];
// Avoid duplicates:
if (in_array($randomLink, $tmp))
{
$i--;
continue;
}
$tmp[] = $randomLink;
echo $randomLink;
}
谢谢
<?php
$links = file('links.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// used this for testing (generated from a file with one link each line (+carriage return)
//$links = ARRAY('foo 1','foo 2','foo 3','foo 4','foo 5','foo 6','foo 7','foo 8','foo 9','foo 10','foo 11','foo 12');
$amount = 3;
shuffle($links);
$rand_list = array_slice($links, 0, $amount);
foreach ($rand_list AS $key => $link) {
print $link.'</br>';
}
?>
考虑每行 1 个链接:
$links = file("dati.txt");
$numLinks = count($links);
$randomIndex = rand(0, $numLinks - 1);
$randomLink = $links[$randomIndex];
echo $randomLink;
获取更多链接只是一个循环问题:
$links = file("dati.txt");
$numLinks = count($links);
$tmp = array();
for ($i = 0; $i < min(5, $numLinks); $i++)
{
$randomIndex = rand(0, $numLinks - 1);
$randomLink = $links[$randomIndex];
// Avoid duplicates:
if (in_array($randomLink, $tmp))
{
$i--;
continue;
}
$tmp[] = $randomLink;
echo $randomLink;
}
$righe_msg = file("dati.txt");
$num = 5;
$selected = array();
while (count($selected)!=$num)
{
$rand = rand(0,count($righe_msg)-1);
$selected[$rand] = $righe_msg[$rand];
}
$numero=0;
foreach ($selected as $sel)
{
$dato = explode("|", trim($sel));
if (trim($dato[5])=="yes")
{
$numero++;
echo"<tr><td bgcolor='#EEEEEE'>» <a href='$dato[2]'> $dato[1]</a></td></tr> ";
}
}