2012-07-12 89 views
0

我知道幫助作業一般不會在這裏被接受,但我已經被卡住了一個多星期了,所以我會非常感激任何幫助。它在概念上似乎很簡單,但我無法從爆炸文件中獲取該信息到數組中。來自列表數據的PHP數組

目標是有東西來比較從窗體輸入的文本。例如,如果名稱Bob被輸入到名稱字段中,那麼將有方法查看Bob的名稱是否已經在列表中。

這裏是我的最新嘗試:

<?php 
    if(isset($_POST['sname'],$_POST['snumber'],$_POST['courseselect'])) 
    { 
     //Has to be submitted first 
     $studentname = $_POST['sname']; 
     $studentnumber = $_POST['snumber']; 
     $course = $_POST['courseselect']; 
     if(empty($studentname) || empty($studentnumber)) 
     { 
      //make sure all fields are filled in 
      echo "All fields must be filled in";//for if they aren't filled in 
     } 
     else 
     { 
      //if they are filled in 
      $studentfile = "students"; 
      $SF = fopen($studentfile, 'r') or die("$studentfile cannot be opened for reading"); 

      while($studentlist = fgets($SF)) 
      { 
       list ($stoodname, $stoodnumber) = explode('::', $studentlist); 
       $testarray[] = array('$stoodname'); 
       echo $testarray; 
      } 
     } 
     //end of if/else 
    }//end of "has to be submitted" 
?> 

我覺得我只是缺少明顯的東西:(

+0

只注意到你想呼應的陣列 - 嘗試的print_r($ testarray);而不是回聲; – TigerTiger 2012-07-12 09:15:13

+0

它給了我一個巨大的列表「Array([0] => Array([0] => $ standname)」 – WizardOfLoss 2012-07-12 09:17:29

+1

並獲取文件內容到數組中 - 嘗試file() - http://php.net/ manual/en/function.file.php – TigerTiger 2012-07-12 09:17:35

回答

0

假設你的學生檔案是一個CSV與::字段之間:

<?php 
    if(isset($_POST['sname'],$_POST['snumber'],$_POST['courseselect'])) 
    { 
     //Has to be submitted first 
     $studentname = $_POST['sname']; 
     $studentnumber = $_POST['snumber']; 
     $course = $_POST['courseselect']; 
     if(empty($studentname) || empty($studentnumber)) 
     { 
      //make sure all fields are filled in 
      echo "All fields must be filled in";//for if they aren't filled in 
     } 
     else 
     { 
      //if they are filled in 
      $studentfile = "students"; 
      $SF = fopen($studentfile, 'r') or die("$studentfile cannot be opened for reading"); 

      while($studentlist = fgets($SF)) 
      { 
       $testArray=explode('::', $studentlist); 
       for($i=0;$<count($testArray);$i++) 
       { 
        if($testArray[$i]==$studentname) 
        { 
         // You found your match! 
        } 
       } 
       print_r($testArray); 
       unset($testArray); 
      } 
     } 
     //end of if/else 
    }//end of "has to be submitted" 
?> 
+0

學生文件是由CSV單獨分隔的,但有學生名稱和學號,這有點幫助雖然! – WizardOfLoss 2012-07-12 18:55:47

0

您的代碼看起來像可以工作

什麼是部分錯誤:

$testarray[] = array('$stoodname'); 

當您在單引號中放置變量時 - 它將被視爲字符串。

嘗試

$testarray[] = $stoodname; 

// other dirt 

$studentExists = in_array($stoodname, $testarray); 

if($studentExist) { 
    // code 
}