关联数组

时间:2015-09-15 15:28:07

标签: php arrays multidimensional-array

我是表格中的新数组。我试图摆脱这一行中的关联数组

  

( “F001”=> “中一”, “F002”=> “中B”, “F003”=> “中C”, “F004”=> “中d”, “F005”=> “E”, “F006”=> “中F”, “F007”=> “中G”, “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>

1 个答案:

答案 0 :(得分: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的最新帖子有信息,而第5个标签(因为0索引)是'值'。