嗨,我有一个脚本,是随机显示5图像为我的网站,但我需要给每个图像一个不同的链接。我有一个朋友帮助与代码,因为我是超级新的php,所以任何帮助任何人可以给我将是了不起的!我在我的原始代码中加载了更多的图像,但我认为没有必要把它们都放在这里。
这是我的代码
<?php
$images=array( // list of files to rotate - add as needed
"images/Austin-Mahone-2.jpg",
"images/Boys-Like-Girls-1.jpg",
"images/Boys-Like-Girls-2.jpg",
"images/Boys-Like-Girls-3.jpg",
"images/It-Boys-5.jpg" );
shuffle($images);
echo '<div class="images">';
$i = 0;
while($i < 5){
echo '<img src="'.$images[$i].'" />';
$i++;
}
echo '</div>';
?>
如上所述的关联数组方法。
<?php
$images = array(
array("src" => "images/Austin-Mahone-2.jpg", "url" => "http://URL1"),
array("src" => "images/Boys-Like-Girls-1.jpg", "url" => "http://URL2"),
array("src" => "images/Boys-Like-Girls-2.jpg", "url" => "http://URL3"),
array("src" => "images/Boys-Like-Girls-3.jpg", "url" => "http://URL4"),
array("src" => "images/It-Boys-5.jpg", "url" => "http://URL15")
);
shuffle($images);
echo '<div class="images">';
foreach ($images as $image) {
echo '<a href="'.$image["url"].'"><img src="'.$image["src"].'" /></a>';
}
echo '</div>';
?>
创建一个链接数组,并将它们与您的图像组合。然后你可以做一个简单的foreach
循环来输出它们:
$links = array('link1', 'link2', 'link3'); // etc.
$combined = array_combine($links, $images);
foreach ($combined as $link => $image) {
echo '<a href="' . $link . '"><img src="' . $image . '" /></a>';
}
如果每个图像每次都有相同的链接,您可以创建一个关联数组,如下所示:
$images = array(
'http://www.google.com' => 'Google',
'http://www.bing.com' => 'Bing',
'http://www.yahoo.com' => 'Yahoo'
);
. .然后按上面的方式循环:
foreach ($images as $link => $image) {
...
}
尝试PHP关联数组:
<?php
$images=array(
array(
"image" => "images/Austin-Mahone-2.jpg",
"link" => "http://yourlink1.com"
),
array(
"image" => "images/Boys-Like-Girls-1.jpg",
"link" => "http://yourlink2.com"
),
array(
"image" => "images/Boys-Like-Girls-2.jpg",
"link" => "http://yourlink3.com"
)
);
shuffle($images);
echo '<div class="images">';
$i = 0;
while($i < 5){
echo '<a href="'.$images[$i]['link'].'"><img src="'.$images[$i]['image'].'" /></a>';
$i++;
}
echo '</div>';
?>
这样你的数组$images
包含X个关联数组,每个关联数组包含['image']
和['link']
的值。
阅读更多关于这些数组(和其他)在这里:http://www.w3schools.com/php/php_arrays.asp