我在下面使用此脚本在网站上创建随机背景图像。它包含数组项并将它们附加到变量$ selectedBg。如何用PHP从数组中存储和调用变量
<?php
$bg = array('background-1.jpg', 'background-2.jpg', 'background-3.jpg', 'background-4.jpg', 'background-5.jpg'); // array of filenames
$i = rand(0, count($bg)-1); //generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>
<style type="text/css">
body{
background: url(<?php bloginfo('template_url'); ?>/images/backgrounds/<?php echo $selectedBg; ?>) no-repeat;
}
</style>
我想那么采取什么是$ selectedBg,将其存储为一个全局变量在我的wordpress isntallation其他PHP文件中使用,并做到每个变量产生不同的输出开关的情况下来自阵列。假设它是'background-1.jpg'作为$ selectedBg的值,那么我想输出文本。如果它是'background-2.jpg'作为$ selectedBg的值,那么我想输出不同的文本,依此类推。
我该如何编写检查存储在$ selectedBg中的代码?我迷路试图采取
switch ($selectedBg) {
case "$selectedBg == 'background-1.jpg'":
echo "whatever";
break;
或等值。
为什么我做这个全局的原因是我在header.php中的代码,但我需要看看什么类型的背景显示在页面上输出某些文本。如果是background-1.jpg我想要TEXT A;如果background-2.jpg我想要TEXT B;等等
'“$ bg [$ i]”'是没有意义的。你所做的只是将你的值包装在一个字符串中,这是多余的。为什么不只是'$ foo = $ bg [$ i]'? –
1)只要做:'$ selectedBg = $ bg [array_rand($ bg)];'2)关联数组:'Array(“background-1,jpg”=>“this text”,...)' – Rizier123
你这么多;你比我聪明多了! – HollerTrain