我有一个脚本将冲浪者重定向到我网站的各个部分。例如,当我将冲浪者发送到script.php?car=bmw
时,它会将冲浪者重定向到http://www.mywebsite.com/bmw
这是脚本的样子:
<?php
$array = array(
"bmw" => "http://www.mywebsite.com/bmw",
"toyota" => "http://www.mywebsite.com/toyota",
"mercedes" => "http://www.mywebsite.com/mercedes"
);
$car = $_GET['url'];
header("Location: " . $array[$car]);
?>
现在我想将冲浪者重定向到随机车,例如
"bmw" => "http://www.mywebsite.com/bmw/x1","http://www.mywebsite.com/bmw/x3","http://www.mywebsite.com/bmw/x5",
"toyota" => "http://www.mywebsite.com/toyota/yaris", "http://www.mywebsite.com/toyota/avensis", "http://www.mywebsite.com/toyota/corolla",
"mercedes" => "http://www.mywebsite.com/mercedes/e", "http://www.mywebsite.com/mercedes/s", "http://www.mywebsite.com/mercedes/d"
因此,当我将冲浪者发送到script.php?car=bmw
时,脚本会将用户重定向到bmw部分的随机页面之一。
我可以使用一个数组吗?
答案 0 :(得分:2)
您可以使用array_rand
-
将它们存储为 -
"bmw" => "http://www.mywebsite.com/bmw/x1,http://www.mywebsite.com/bmw/x3,http://www.mywebsite.com/bmw/x5",
并使用 -
header("Location: " . array_rand(explode(',', $array[$car])));
答案 1 :(得分:2)
您可以重构数组以包含这种情况下的子类型。像
这样的东西<?php
$array = array(
"bmw" =>array(
'car1' => "http://www.mywebsite.com/bmw/car1",
'car2' => "http://www.mywebsite.com/bmw/car2",
'car3' => "http://www.mywebsite.com/bmw/car3",
'car4' => "http://www.mywebsite.com/bmw/car4",
),
"toyota" =>array(
'car5' => "http://www.mywebsite.com/toyota/car5",
'car6' => "http://www.mywebsite.com/toyota/car6",
),
"mercedes" =>array(
'car7' => "http://www.mywebsite.com/mercedes/car7",
'car8' => "http://www.mywebsite.com/mercedes/car8",
),
);
$car = $_GET['url'];
header("Location: " . $array[$car][array_rand($array[$car]))];
?>
答案 2 :(得分:1)
<?php
$array = array(
"bmw" => array("http://www.mywebsite.com/bmw/x1","http://www.mywebsite.com/bmw/x3","http://www.mywebsite.com/bmw/x5"),
"toyota" => array("http://www.mywebsite.com/toyota/yaris","http://www.mywebsite.com/toyota/avensis","http://www.mywebsite.com/toyota/corolla",),
"mercedes" => array("http://www.mywebsite.com/mercedes/s","http://www.mywebsite.com/mercedes/d")
);
$car = $_GET['url'];
$rand = rand(0,count($array[$car])-1)
header("Location: " . $array[$car][$rand]);
&#13;
答案 3 :(得分:1)
您需要使用多维数组和array_rand()函数。请尝试考虑以下代码:
$array = array(
"bmw" => array("http://www.mywebsite.com/bmw/x1","http://www.mywebsite.com/bmw/x3","http://www.mywebsite.com/bmw/x5"),
"toyota" => array("http://www.mywebsite.com/toyota/yaris", "http://www.mywebsite.com/toyota/avensis", "http://www.mywebsite.com/toyota/corolla"),
"mercedes" => array("http://www.mywebsite.com/mercedes/e", "http://www.mywebsite.com/mercedes/s", "http://www.mywebsite.com/mercedes/d")
);
$car = $_GET['url'];
header("Location: " . $array[$car][array_rand($array[$car],1)]);
现在它有一个可以随机化的值数组(array_rand()可以为你完成这项工作),而不是拥有一个bmw&#39;的值。