【问题标题】:Php array only shows my last pushed valuephp数组只显示我最后推送的值
【发布时间】: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


【解决方案1】:

您最好将这两个值作为一项推送到数组中,目前您将它们作为两项添加...

array_push($list, ["name" => $c, "dream" => $f]);

然后将它们打印出来,您将为每个细节引用数组的一部分...

foreach ($list as $z) {
    echo "{$z['name']} has this as dream: {$z['dream']} \n";
    echo "\n";
}

【讨论】:

  • $list = ["name" =&gt; $c, "dream" =&gt; $f];