2015-09-15 38 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)是'值'。