【发布时间】:2025-12-09 20:20:05
【问题描述】:
我制作了一个 php 脚本,您必须在其中填写姓名和他们的梦想,但它无法正常工作。脚本必须输出名字和他们的梦想,但我得到双重名字或双重梦想。
<?php
echo "How many friends should i ask for their dream?\n";
$a = readline("");
$naam = "What is your name?\n";
$droom = "What is your dream?\n";
$list = [];
if (is_numeric($a)) {
for ($x = 1; $x <= $a; $x++) {
echo $name;
$c = readline("");
echo $dream;
$f = readline("");
array_push($list, $c, $f);
}
} else {
echo "'$a' is not a number, try again.";
exit;
}
foreach ($list as $z) {
echo "$c has this as dream: $f \n";
echo $z;
echo "\n";
}
?>
【问题讨论】:
-
因为您的输出使用了 $c 和 $f,这只会等于上面循环中的最后一个值。如果您问了 3 个朋友,当您在底部执行下一个循环以显示输出时,这些变量将包含第 3 次迭代的值。在那之后它们不会改变,这就是你会看到重复的原因。
标签: php associative-array