Frage

I have an array where the key is a filename and the value is the name of a fish. Right now, this loop prints out text for a randomly chosen fish, then it loops through the img directory and prints every image. How do I "link" it so that the image of the fish corrsponse with the name? Like, if it outputs Nice one! You caught a small-mouth bass! I would then want it to only output smbass.gif.

The php file is in the root, and the images folder is root/img/smbass.gif, e.g.

<p class="fishes">
<form action="fishing.php" method="post">
    <?php

    $fish = array('catfish.gif' => 'catfish', 'lmbass.gif' => 'large-mouth bass', 'smbass.gif' => 'small-mouth bass', 'shiner.gif' => 'shiner', 'perch.gif' => 'perch', 'pickerel.gif' => 'pickerel', 'minnow.gif' => 'minnow', 'sunfish.gif' => 'sunfish');
    $rand = array_rand($fish);
    //link file name (key) to value

    echo "Nice one! You caught a " . $fish[$rand] . "!";

    $files = scandir('img');
        if ($files !== false) {
            foreach($files as $f) {
                if ($f == '..' || $f == '.' || substr($f, -strlen(".DS_Store")) === ".DS_Store") continue;
            echo '<li class="fish_pic"><img src="img/'.$f.'" alt="'.$f.'" title="" class="fish"></li>'."\n";
            }
        }
    ?>
</p><!-- close class="fishes" -->
    <p><input type="submit" class="btn btn-primary" value="Go Fishing!"></p>
</form>
War es hilfreich?

Lösung

Try something like this:

<form action="fishing.php" method="post">

<?php
$fish = array(
    'catfish.gif' => 'catfish', 
    'lmbass.gif' => 'large-mouth bass', 
    'smbass.gif' => 'small-mouth bass', 
    'shiner.gif' => 'shiner', 
    'perch.gif' => 'perch', 
    'pickerel.gif' => 'pickerel', 
    'minnow.gif' => 'minnow', 
    'sunfish.gif' => 'sunfish'
    );

$rand = array_rand($fish);
$sImageOut = "";

//check the image
// - yes, error supression is normally evil
// - and assigning variables in this way isn't exactly pretty
// ... but it works
if(list($iImgX, $iImgY, $iImgType, $sImgAttr) = @getimagesize(__DIR__ . '/img/' . $rand)) {
  $sImageOut = "<div><img src=\"img/{$rand}\" alt=\"{$fish[$rand]}\" style=\"width: {$iImgX}px; height: {$iImgY}px; border: 1px solid #cccccc;\" /></div>\n";
}

//output
echo "<p>Nice one! You caught a {$fish[$rand]}!</p>\n{$sImageOut}";
?>

<p><input type="submit" class="btn btn-primary" value="Go Fishing!"></p>
</form>

Since the image name is the key and array_rand() returns the key ... $rand contains the image filename.

I'm using getimagesize() in there so that if, for some reason your image doesn't exist, it won't create "duff" output - not the tidiest code but it works as an example.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top