I'm trying to accomplish something using an associative array as suggested somewhere else here on Stackoverflow, but I've never used arrays so I'm struggling. I've looked it up but only to be left more confused than I was!
Here's the deal: I want to display a random image as the background of a Worpdress site, AND show the name of the photographer who took the image as well. So I've created a function that includes an associative array that associates the image with the photographer, and a little script to retrieve both the photo and the photographer's name. This is my function:
function bg_image_info() {
$creditsList = array(
"1" => "Photographer 1",
"2" => "Photographer 2",
"3" => "Photographer 3",
...
...
"74" => "Photographer 74"
);
$root = get_stylesheet_directory_uri();
$dir = $root . "/images/bgs/";
$random = mt_rand(1,74);
$path = $root . "/images/bgs/bg_" . $random . ".jpg";
$credits = $creditsList["" . $random . ""];
return array($path, $credits);
}
It works pretty well, but there's one catch. I need to use the two values $path and $credits in two different places ($path as a "src" attribute, $credits in a "p" tag), so what I tried to do after some research was write these two more functions:
function bg_image_path() {
list($bgPath, $bgCredits) = bg_image_info($path, $credits);
echo $bgPath;
}
function bg_image_credits() {
list($bgPath, $bgCredits) = bg_image_info($path, $credits);
if($bgCredits) {
echo "Photo " . $bgCredits . "";
}
}
and then call each one where I need to value to be. But it looks like the two functions use a different $random value because the photo and the credits don't match (they do if I replace mt_rand() with a fixed value for test purposes).
So how do I echo the two values returned by the first function so that the same $random value is used?
I would really really appreciate any help, thank you!
Aucun commentaire:
Enregistrer un commentaire