我试图永久重置阵列中每个学生的平均分数,但没有运气。我正在使用&amp ;;将包含所有学生的数组传递给我的函数。运算符,以便通过引用传递。我运行我的函数,重置平均标记并在表格中打印出结果,并指示平均标记已在方法内重置。然后我在方法之外的数组上调用var_dump()来检查更改是否仍然有效。 var_dump()的输出显示平均标记不变:'(。任何帮助都会非常感激。
ID Name Surname Address Telephone Average
123345(M) Roger Fenech USA 21212121 0
835392(M) Chris Tabone UK 21456780 0
693648(M) Thomas Grech Spain 21854595 0
483582(M) Michael Abela Turkey 24872639 0
742652(M) Stan Galea France 21951357 0
的var_dump():
array(5) { [0]=> array(6) { ["ID"]=> string(9) "123345(M)" ["Name"]=> string(5) "Roger" ["Surname"]=> string(6) "Fenech" ["Address"]=> string(3) "USA" ["Telephone"]=> int(21212121) ["Average"]=> int(100) } [1]=> array(6) { ["ID"]=> string(9) "835392(M)" ["Name"]=> string(5) "Chris" ["Surname"]=> string(6) "Tabone" ["Address"]=> string(2) "UK" ["Telephone"]=> int(21456780) ["Average"]=> int(78) } [2]=> array(6) { ["ID"]=> string(9) "693648(M)" ["Name"]=> string(6) "Thomas" ["Surname"]=> string(5) "Grech" ["Address"]=> string(5) "Spain" ["Telephone"]=> int(21854595) ["Average"]=> int(60) } [3]=> array(6) { ["ID"]=> string(9) "483582(M)" ["Name"]=> string(7) "Michael" ["Surname"]=> string(5) "Abela" ["Address"]=> string(6) "Turkey" ["Telephone"]=> int(24872639) ["Average"]=> int(88) } [4]=> array(6) { ["ID"]=> string(9) "742652(M)" ["Name"]=> string(4) "Stan" ["Surname"]=> string(5) "Galea" ["Address"]=> string(6) "France" ["Telephone"]=> int(21951357) ["Average"]=> int(76) } }
代码:
<html>
<head>
<title>PHP Test</title>
</head>
<style type="text/css">
table{text-align: center}
</style>
<body>
<?php
$students = array
(
array(
'ID' => '123345(M)',
'Name' => 'Roger',
'Surname' => 'Fenech',
'Address' => 'USA',
'Telephone' => 21212121,
'Average' => 100
),
array(
'ID' => '835392(M)',
'Name' => 'Chris',
'Surname' => 'Tabone',
'Address' => 'UK',
'Telephone' => 21456780,
'Average' => 78
),
array(
'ID' => '693648(M)',
'Name' => 'Thomas',
'Surname' => 'Grech',
'Address' => 'Spain',
'Telephone' => 21854595,
'Average' => 60
),
array(
'ID' => '483582(M)',
'Name' => 'Michael',
'Surname' => 'Abela',
'Address' => 'Turkey',
'Telephone' => 24872639,
'Average' => 88
),
array(
'ID' => '742652(M)',
'Name' => 'Stan',
'Surname' => 'Galea',
'Address' => 'France',
'Telephone' => 21951357,
'Average' => 76
)
);
function resetAverage(&$students){
echo "<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Address</th>
<th>Telephone</th>
<th>Average</th>
</tr>" ;
foreach ($students as $student) {
echo "<tr>";
unset($student["Average"]);
$student["Average"] = 0;
foreach ($student as $key => $value) {
echo "<td>" . $value . "</td>";
}
echo '</tr>';
}
echo "</table>";
}
resetAverage($students);
echo "<pre>" . var_dump($students) . "</pre>";
?>
</body>
</html>
答案 0 :(得分:3)
您还需要在foreach
循环中使用引用:
foreach ($students as &$student) {
否则$student
是数组元素的副本,因此unset($student["Average"])
仅影响副本,而不影响原始数组。
答案 1 :(得分:1)
您还需要通过引用传递$student
数组:foreach ($students as &$student)
,否则每个学生数组将在迭代时被复制。