-1

我正在努力弄清楚如何创建一个 php 代码,以在这个 html 中以随机方式显示图像,以及 href 链接、alt 属性和标题。

<ul>
   <li>
      <img src="http://www.prevention.com/sites/default/files/imagecache/102x104/images/news/featured_images/156854573-raw-meat-lab-628x363.jpg" alt="" title="" class="imagecache imagecache-102x104" height="104" width="102">    
      <p>    <a href="/food/healthy-eating-tips/theres-test-tube-burger-your-future">There?s A Test-Tube Burger In Your Future</a>
      </p>
   </li>
   <li>
      <img src="http://www.prevention.com/sites/default/files/imagecache/102x104/images/news/featured_images/86541117-grocery-shopping-produce-organic-label-mixed-greens-lg.jpg" alt="" title="" class="imagecache imagecache-102x104" height="104" width="102">    
      <p>    <a href="/food/smart-shopping/connecticut-gmo-labeling-law">GMOs?Exposed!</a>
      </p>
   </li>
</ul>

这是我的 PHP 代码。

<?php
    $images = array('healthyfoods', 'mood7', '15_heart',
        'healthyf', 'visuals', 'healthyd', 'health01', 'crackers',
        'mmo', 'oo1', 'mushrooms', 'raw', 'vegetable', 'heal',
        '139572961', '3889');
    $i = rand(0, count($images)-1);
    $selectedImage = "../../images/main_body_image/{$images[$i]}.jpg";
?>
4

3 回答 3

2

使用 PHP 的rand()函数生成一个随机数,然后只需使用该数字来确定要显示的图像。

编辑:

如果变量包含数组索引,则不能将变量嵌入到 PHP 字符串中,它只是不起作用,您需要手动连接字符串,{}括号也会直接打印到您不想要的字符串中,所以采取他们出来:

$selectedImage = "../../images/main_body_image/" . $images[$i] . ".jpg";

一旦你有了你想要的图像$selectedImage,你就可以在你想要的地方创建你的 HTML 代码。echo

// In the middle of your html code where you want to display your random image:
<?php echo '<img src="$selectedImage" height="104" width="102">'; ?>

echo使 PHP 从字面上将该文本打印到您的 HTML 中,因此它应该是 HTML 格式。

于 2013-08-08T18:40:29.907 回答
1

您的问题有很多可能的解决方案。

我会告诉你我会做什么:

  1. 创建一个包含您希望随机显示的图像数据的数组

    1b。如果您有很多图像(100 多张),请只在数组中放入有限的数量以获得更好的性能。限制用于获取图像文件路径的函数中的返回量(数据库查询或文件系统,例如scandir()glob()DirectoryIterator

    1c。我建议您将图像数据存储在 MySQL 数据库中。它更快,您可以用它做更多事情。请参见下面的示例。

  2. 然后随机化图像的顺序,你可以使用类似的东西shuffle()

  3. 用于foreach()循环遍历数组和echo图像

 

因此,例如:

<?php
$images = array();  

// Get the images (just for this example, do it however you like).
// With sql queries ORDER BY RAND() could be used to randomize the results returned, but 
// it depends on the amount of data stored in the db. The more the slower the query will be.
$database->query('SELECT id, name, title, url, anchor_text, path FROM featured_images ORDER BY id LIMIT 10');

// Randomize the images
shuffle($images);

// Echo the randomized images
echo '<ul>';
foreach ($images as $image)
{
    echo '<li>';
    echo '<img src="'.$image->path.'" alt="" title="'.$image->title.'" class="...>';
    echo '<p><a href="'.$image->url.'">'.$image->anchor_text.'</a></p>';
    echo '</li>';
}
echo '</ul>';

 
在示例代码中,我使用了一个基本的 SQL 查询。要使用 SQL 的原生RAND(),可以使用以下查询(注意 LIMIT 10 是可选的,但建议在表包含大量图像时使用,因此根据需要调整 10)(另请阅读来自上面示例中关于性能的 sql 查询)

SELECT id, title, path FROM featured_images WHERE id IN(SELECT id FROM featured_images ORDER BY RAND() LIMIT 10)

 
我不知道您是如何以及是否从中获取图像数据的,但是可以像这样从目录中读取数据(请注意,这种方法不能包含标题和锚文本,请使用上面示例中的数据库变体相反,因为它也更快)

$dir = new DirectoryIterator("/path/to/images");
foreach ($dir as $file)
{
    $images[] = array(
        'path' => $file->getPath(), // file path w/o filename
        'name' => $file->getFilename(),
    );
}  

 
试一试,摆弄它并通读 PHP 手册(我将函数名称与相应的手册页链接)

祝你好运。


编辑:

我正在更新这个答案以an array only solution根据提问者的评论提供:

嗨,Markus,我没有使用 db,因为它只有几张图像,如果我们使用数组,你能给我一些关于在 foreach 循环中编写代码的提示吗?谢谢你,阿奈

 
好的,所以您想使用包含少量图像的数组。我假设您正在将数据“硬编码”到脚本中。开始了:

<?php
// Since the image paths given in your example both conside in the same directory,
// you can create a base_path variable to prevent repeating the path over and over again
$imgBasePath = 'http://www.prevention.com/sites/default/files/imagecache/102x104/images/news/featured_images/';

// Create the array containing the required image data (hard-coded)
$images = array(
    array(
        'path'      => $imgBasePath . '156854573-raw-meat-lab-628x363.jpg',
        'title'     => '',
        'width'     => '102',
        'height'    => '104',

        'link_url'  => '/food/healthy-eating-tips/theres-test-tube-burger-your-future',
        'link_text' => 'There\'s A Test-Tube Burger In Your Future',
    ),

    array(
        'path'      => $imgBasePath . '86541117-grocery-shopping-produce-organic-label-mixed-greens-lg.jpg',
        'title'     => '',
        'width'     => '102',
        'height'    => '104',

        'link_url'  => '/food/smart-shopping/connecticut-gmo-labeling-law',
        'link_text' => 'GMOs-Exposed!',
    ),
);

// Now loop through the $images array and create the desired list
// I'm putting the html into a var to be more flexible of where to echo the created html
$html = '';
foreach ($images as $image)
{
    $html .= '<li>';

    $html .= '<img src="'.$image['path'].'" alt="" title="'.$image['title'].'" class="imagecache imagecache-102x104" width="'.$image['width'].'" height="'.$image['height'].'">';

    $html .= '<p><a href="'.$image['link_url'].'">'.$image['link_text'].'</a></p>';
    $html .= '</li>';
}

// Finally echo the list to the browser
echo '<ul>'.$html.'</ul>';

硬编码意味着您将数据放入未动态更改的脚本中。从数据库中获取数据可以更改(例如更新或添加),因此它是动态的。示例中的完成方式称为硬编码)。

foreach 循环遍历 $images 数组并返回循环内的每个单独的 $image。要访问 $image 数据,可以使用类似的东西$image['path']。很直接。

这是一个关于如何创建数组并在 foreach 循环中使用它们的基本示例。

快乐编码。

于 2013-08-08T19:31:58.513 回答
0
<?php
   define ('CRLF' , "\r\n");
   $images = array('healthyfoods|text desc1',
                          'mood7|text desc2',
                       '15_heart|text desc3',
                       'healthyf|text desc4',
                        'visuals|text desc5',
                       'healthyd|text desc6'); // you get the idea
   $i = mt_rand(0, count($images)-1);
   list ($filename, $alttext) = explode("|", $images[$i]);
   $selectedImage = "../../images/main_body_image/" . $filename . ".jpg";
   list($width, $height, $type, $attr) = getimagesize($selectedImage);
   $ho = '   <img src="' . $selectedImage . '" alt="' . $alttext . '" title="' . $alttext . '" ' . $attr . ' />' . CRLF;
 ?>

在您的 HTML 代码中:

<ul>
  <li>
    <?php echo $ho; ?>
    <p> ...
于 2013-08-08T20:02:51.140 回答