2013-06-22 109 views
-1

我想讓這個網站來練習我的編程。如何在PHP中隨機選擇數組條目?

<html> 
    <title>VidVoter</title> 

    <head> 
     <link rel="stylesheet" type="text/css" href="stylesheet.css"> 
     <div id="welcome">Welcome to VidVoter!</div> 


     <a href="file://localhost/Users/alihashemi/Desktop/vidvoter.html"> 
      <div id="vote1">Vote for this video</div> 
     </a> 


     <a href="file://localhost/Users/alihashemi/Desktop/vidvoter.html"> 
      <div id="vote2">Vote for this video</div> 
     </a> 
    </head> 

    <?php 
    $videos = array("xrCTiImIWk4" , "WCpfVPY4J6I" , "__2ABJjxzNo" , "y7tI1E6kp0o" , "-NSL_DgwCYw"); 
    $rand = array_rand($videos); 
    $rand_key = isset($_GET['id']) ? $_GET['id'] : $rand; 
    ?> 


    <p> 

      <h1><iframe width="560" height="315" src="http://www.youtube.com/embed/<?php .$rand_key.?>" frameborder="0" allowfullscreen></iframe></h1> 

      <h2><iframe id="vid2" width="560" height="315" src="http://www.youtube.com/embed/<?php .$rand_key.?>" frameborder="0" allowfullscreen></iframe><h2> 


    </p> 
</html> 

我似乎無法弄清楚如何從視頻陣列中隨機選擇視頻並將其放置在網站上。你能幫我解決嗎?

+0

你甚至有服務器安裝?你使用文件URL的事實讓我相信你不知道。 – Daedalus

回答

1

你試過..

$rand_key = isset($_GET['id']) ? $_GET['id'] : $rand[0]; 
+1

如果您僅挑選一個條目,array_rand()將返回隨機條目的鍵。 – DevZer0

2

由於DevZer0評論,array_rand()返回一個數組的關鍵,而不是它的價值。在你的例子中,你會想要

$rand_key = isset($_GET['id']) ? $_GET['id'] : $video[$rand];