使用 readline 将循环数据添加到关联数组中
Adding looped data into associative array with readline
写一个小程序问一些人他们的梦想是为了好玩。我正在尝试将数据放入关联数组中。我希望它像这样出来(例如三个名字:
How many people should I ask their dreams?
*number*
What is your name?
*name*
What is your dream?
*dream*
name's dream is: dream
我的代码如下:
<?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;
$dreams[] = readline() . PHP_EOL;
echo "What is your dream?" . PHP_EOL;
$dreams[] = readline() . PHP_EOL;
}
echo "In jouw bucketlist staat: " . PHP_EOL;
foreach ($dreams as $key => $value) {
echo $key . "'s dream is: " . $value;
}
} else {
exit($hoeveel . ' is geen getal, probeer het opnieuw');
}
?>
它一直返回这个:
0's dream is: *name*
1's dream is: *name*
etcetera.
当您使用 foreach ($dreams as $key => $value)
从 $dreams
数组中读取值时,您期望名称作为键,但这不是您插入值的方式。您可以像这样使用名称作为数组键:
for ($i = 1; $i <= $many; $i++) {
echo "What is your name?" . PHP_EOL;
// set a name variable here
$name = readline() . PHP_EOL;
echo "What is your dream?" . PHP_EOL;
// then use that variable as the array key here
$dreams[$name] = readline() . PHP_EOL;
}
写一个小程序问一些人他们的梦想是为了好玩。我正在尝试将数据放入关联数组中。我希望它像这样出来(例如三个名字:
How many people should I ask their dreams?
*number*
What is your name?
*name*
What is your dream?
*dream*
name's dream is: dream
我的代码如下:
<?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;
$dreams[] = readline() . PHP_EOL;
echo "What is your dream?" . PHP_EOL;
$dreams[] = readline() . PHP_EOL;
}
echo "In jouw bucketlist staat: " . PHP_EOL;
foreach ($dreams as $key => $value) {
echo $key . "'s dream is: " . $value;
}
} else {
exit($hoeveel . ' is geen getal, probeer het opnieuw');
}
?>
它一直返回这个:
0's dream is: *name*
1's dream is: *name*
etcetera.
当您使用 foreach ($dreams as $key => $value)
从 $dreams
数组中读取值时,您期望名称作为键,但这不是您插入值的方式。您可以像这样使用名称作为数组键:
for ($i = 1; $i <= $many; $i++) {
echo "What is your name?" . PHP_EOL;
// set a name variable here
$name = readline() . PHP_EOL;
echo "What is your dream?" . PHP_EOL;
// then use that variable as the array key here
$dreams[$name] = readline() . PHP_EOL;
}