2015-09-15 83 views
-2

的這個陣列中形成的目的,我新。我試圖在此行中擺脫關聯數組的什麼是關聯數組

( 「F001」=> 「一」, 「F002」=> 「B」, 「F003」=> 「C」, 「F004」= > 「d」, 「F005」=> 「E」, 「F006」=> 「F」, 「F007」=> 「克」, 「F008」=> 「H」, 「F009」=> 「i」 的, 「F010」=>「j」)

並使之成爲(「F001」,「F002」等),但程序無法正常工作。如果我把它放回去,它會起作用。我的問題是爲什麼它不會工作,如果我擺脫了關聯數組?

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    </head> 
 
    <body> 
 
    <?php 
 
     if (isset($_POST['search'])) { 
 
      // move $students into the if statement cause we won't 
 
      // need it unless they're searching 
 
      $students = array (
 
       array ("F001"=>"a","F002"=>"b","F003"=>"c","F004"=>"d","F005"=>"e","F006"=>"f","F007"=>"g","F008"=>"h","F009"=>"i","F010"=>"j"), 
 
       array ("albert","berto","charlie","david","earl","francis","garry","harry","irish","james"), 
 
       array (1,2,3,3,2,1,2,1,3,1) 
 
      ); 
 

 
      $idNumber = $_POST['search']; 
 
      // we can use isset here because the student id *is* the key. 
 
      // if it was the value, than we would use array_search() and 
 
      // check if it returned false 
 
      if (isset($students[0][$idNumber])) { 
 
       // array_keys returns the keys of an array as an array, 
 
       // allowing us to find the numerical index of the key 
 
       $studentIndex = array_search($idNumber,array_keys($students[0])); 
 
       // printf basically allows for formatted echoing. %s means 
 
       // a string. %d means a number. You then pass in your 
 
       printf('Student ID: %s<br>Name: %s<br>Grade: %d', $idNumber, $students[1][$studentIndex], $students[2][$studentIndex]); 
 
      } 
 
      else { 
 
       // use htmlspecialchars() to encode any html special characters cause never trust the user 
 
       printf('No student with ID "%s" found.', htmlspecialchars($idNumber)); 
 
      } 
 
     } 
 
    ?> 
 
     <form action="" method="POST"> 
 
      Id number: <input type="text" name="search"> 
 
      <input type="submit" value="search"> 
 
     </form> 
 
    </body> 
 
</html>

+0

「程序無法正常工作」是模糊的定義。什麼都行不通,會不會崩潰?在哪一行?它會引入一個奇怪的行爲?它是什麼 ?你的代碼更改是什麼讓程序「不工作」? – alfasin

+0

@slugonamission在片的上面只鍵碼被使用,這意味着關聯數組* *可以被轉換爲一個簡單的陣列,即,除非有,我們不能看到代碼的另一部分 - 這使用它們。 – alfasin

+0

assumnig你寫的代碼,你應該知道,如果你改變了陣列結構,你也應該適應代碼來搜索新的陣列結構的項目.. –

回答

0

爲什麼,如果你刪除它在評論中提到不起作用:

// we can use isset here because the student id *is* the key. 
// if it was the value, than we would use array_search() and 
// check if it returned false 

這一決定背後的原因是沒有從例子清楚,但這些鍵代表的字母可能對更大的系統有更廣泛的含義,因此決定採取聯想。

作爲關聯數組的目的,它可以使搜索特定項更簡單,特別是在多維數組。它也可以提高可讀性。

試圖瞭解以下將是一個痛苦的最好: $posts[0][1][0][7][4] = 'value';

凡爲了解下面是更容易一些: $posts[newest][1][information][tags][4] = 'value';

使用關聯數組的上面更容易地看到,在一系列帖子中,索引爲1的最新帖子有信息,而第五個標籤(因爲索引爲0)是'值'。