如何为for循环中生成的每个项目分配唯一的静态字符串?

时间:2010-09-23 13:32:16

标签: php

如何为for循环中的变量分配唯一的静态字符串?我正在尝试为缩略图列表分配唯一的描述和alt标记。我设法得到循环来生成缩略图,但我无法弄清楚如何根据值的条件为每个缩放分配唯一值。这是for循环:

    <?php


    for ( $project=1; $project<=40; $project++  ) {                        

        echo "

          <a href=\"#\" class=\"thumb\">
            <img src=\"images/thumbs/$project.jpg\" width=\"300\" height=\"140\" alt=\"$projectname\" title=\"$projectname\" />
            <span class=\"client\">$projectname</span><span class=\"description\">$type</span>
          </a>

        ";
    }


?>

我在for循环之前尝试了这个但是没有用...

    if ( $project = 1 ) {
            $projectname = "client1";
            $type = "Interactive Brochure Design";
    }

    else if ( $project = 2 ) {
            $projectname = "client2";
            $type = "Site Design";
    }

3 个答案:

答案 0 :(得分:1)

if ( $project == 1 ) {
        $projectname = "client1";
        $type = "Interactive Brochure Design";
}

else if ( $project == 2 ) {
        $projectname = "client2";
        $type = "Site Design";
}

=设置变量并且不进行比较。 ==比较

当然,您的项目可能有更优雅的方式......

答案 1 :(得分:1)

您通常会将每个项目存储在一个数组中,这样您就可以轻松地遍历它们。存储在数组中的值可以是某个“project”类的对象,也可以是关联数组,如下所示:

$projects = array(
    array(
        'name' => 'client1',
        'type' => 'Interactive Brochure Design',
        'filename' => 'client1.jpg',
    ),
    array(
        'name' => 'client2',
        'type' => 'Site Design',
        'filename' => 'client2.jpg',
    ),
);

foreach($projects as $project)
    echo '

      <a href="#" class="thumb">
        <img src="images/thumbs/'.$project['filename'].'" width="300" height="140" alt="'.$project['name'].'" title="'.$project['name'].'" />
        <span class="client">'.$project['name'].'</span><span class="description">'.$project['type'].'</span>
      </a>

    ';

答案 2 :(得分:0)

这就是阵列的用途。类似的东西:

$projects = array(
    array('name' => 'client1', 'type' => 'Interactive Brochure Design'),
    array('name' => 'client2', 'type' => 'Site Design'),
);

for ($n=0; $n<count($projects); ) {

    $projectname = $projects[$n]['name'];
    $type = $projects[$n]['type'];
    $project = ++$n;

    echo "

      <a href=\"#\" class=\"thumb\">
        <img src=\"images/thumbs/$project.jpg\" width=\"300\" height=\"140\" alt=\"$projectname\" title=\"$projectname\" />
        <span class=\"client\">$projectname</span><span class=\"description\">$type</span>
      </a>
    ";
}

或者你也可以使用foreach

foreach ($projects as $project) {
    echo '<div>name: ' . $project['name'] . '</div>
          <div>type: ' . $project['type'] . '</div>';
}

codepad

上查看