[英]PHP accessing one element in an array
在此示例中,我从文本文件中读取数据,然后根据数据是从男性还是女性向表输出数据库。 我在这行上遇到麻烦:echo“ $ male_votes ['class-int']”; 我收到解析错误。 我只是试图访问数组$ 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);
?>
尝试这样:
echo "<td> ${male_votes['class-int']}</td>";
或像这样:
echo "<td> {$male_votes['class-int']}</td>";
或像这样:
echo '<td> '.$male_votes['class-int'].'</td>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.