PHP访问数组中的一个元素

时间:2015-10-29 04:12:17

标签: php arrays

在这个例子中,我正在读取文本文件中的数据,然后我输出数据基于数据是从男性还是女性进入表格。我遇到了问题:echo" $ male_votes ['类-INT']&#34 ;; 我收到一个解析错误。我只是试图访问数组$ male_votes中的第一个元素,名为" class-int"。

<?php
//Keep track of male votes
$male_votes =array("class-int" => 0, "class-gui" => 0, "class-net" => 0, "class-oop"=> 0);
//Keep track of the female votes
$female_votes = array("class-int" => 0, "class-gui" => 0, "class-net" => 0, "class-oop" => 0);

//Open the file for reading
$myfile = fopen("results.txt", "r") or die("Unable to open file!");

echo "<table border='1'>";
echo "<tr> <th> <strong> Class </strong> </th>";
echo "<th> <strong> Males </strong> </th>";
echo "<th> <strong> Females <strong> </th>";
echo "<th> <strong> Total </strong> </th> </tr>";
echo "<tr> <td> Internet Development </td>";

// Output one line until end-of-file
while(!feof($myfile)) {
   //Read a single line from the file
   $line = fgets($myfile);

   //Make sure we didn't read an empty line
   if(strlen($line) >0)
   {
       $class = substr($line,0,9);
       $gender = substr($line,10,1);
       echo "$class<br>";
       if($gender == 'M')
       {
            $male_votes[$class]++;
       }
       else
       {
           $female_votes[$class]++;
       }
   }
}
echo "<td> $male_votes['class-int']</td>";

// echo"<td> $male_votes[$class] </td>";
// echo"<td> $female_votes[$class]</td>";
// echo "<td> $male_votes[$class] + $female_votes[$class]";

fclose($myfile);
?>

1 个答案:

答案 0 :(得分:1)

试试这样:

echo "<td> ${male_votes['class-int']}</td>";

或者像这样:

echo "<td> {$male_votes['class-int']}</td>";

或者像这样:

echo '<td> '.$male_votes['class-int'].'</td>';