向多维数组 PHP 添加值而不覆盖上次添加的值
Adding values to multidimensional array PHP without overwritting last added value
我在向关联多维数组添加值并将它们回显时遇到问题。最后添加的值是被回显的值。我尝试在 $dreams[$name]
旁边玩 $j
但它只会回显第一个字母。我的代码如下:
<?php
echo "How many people should I ask their dreams?" . PHP_EOL;
$many = readline();
$dreams = [];
if (is_numeric($many)) {
for ($i = 1; $i <= $many; $i++) {
echo "What is your name?" . PHP_EOL;
$name = readline();
echo "How many dreams are you going to enter?" . PHP_EOL;
$numberDreams = readline();
if (is_numeric($numberDreams)) {
for ($j = 1; $j <= $numberDreams; $j++) {
echo "What is your dream?" . PHP_EOL;
$dreams[$name] = readline();
}
}
}
echo "In jouw bucketlist staat: " . PHP_EOL;
foreach ($dreams as $key => $value) {
echo $key . "'s dream is: " . $value . PHP_EOL;
}
} else {
exit($many . ' is not a number, try again.');
}
?>
你需要
$dreams[$name][] = readLine();
这会在 $dreams[$name]
中为每个输入的值创建一个新的数组条目。否则,是的,你每次都用不同的值覆盖 $dreams[$name]
。
然后要输出,你需要两个循环,一个用于名字,一个用于梦想——它应该是输入过程的镜像——因为实际上你是在反向进行这个过程,用相同的数据结构:
foreach ($dreams as $name => $entries) {
echo $name . "'s dreams are: ". PHP_EOL;
foreach ($entries as $dream)
{
echo $dream.PHP_EOL;
}
}
您可以使用 array_push()
函数,您可以将这一行 $dreams[$name] = readline();
替换为 array_push($dreams[$name], readline());
我在向关联多维数组添加值并将它们回显时遇到问题。最后添加的值是被回显的值。我尝试在 $dreams[$name]
旁边玩 $j
但它只会回显第一个字母。我的代码如下:
<?php
echo "How many people should I ask their dreams?" . PHP_EOL;
$many = readline();
$dreams = [];
if (is_numeric($many)) {
for ($i = 1; $i <= $many; $i++) {
echo "What is your name?" . PHP_EOL;
$name = readline();
echo "How many dreams are you going to enter?" . PHP_EOL;
$numberDreams = readline();
if (is_numeric($numberDreams)) {
for ($j = 1; $j <= $numberDreams; $j++) {
echo "What is your dream?" . PHP_EOL;
$dreams[$name] = readline();
}
}
}
echo "In jouw bucketlist staat: " . PHP_EOL;
foreach ($dreams as $key => $value) {
echo $key . "'s dream is: " . $value . PHP_EOL;
}
} else {
exit($many . ' is not a number, try again.');
}
?>
你需要
$dreams[$name][] = readLine();
这会在 $dreams[$name]
中为每个输入的值创建一个新的数组条目。否则,是的,你每次都用不同的值覆盖 $dreams[$name]
。
然后要输出,你需要两个循环,一个用于名字,一个用于梦想——它应该是输入过程的镜像——因为实际上你是在反向进行这个过程,用相同的数据结构:
foreach ($dreams as $name => $entries) {
echo $name . "'s dreams are: ". PHP_EOL;
foreach ($entries as $dream)
{
echo $dream.PHP_EOL;
}
}
您可以使用 array_push()
函数,您可以将这一行 $dreams[$name] = readline();
替换为 array_push($dreams[$name], readline());