寫一個小程式問一些人他們的夢想是為了好玩。我正在嘗試將資料放入關聯陣列中。我希望它像這樣出來(例如三個名字:
How many people should I ask their dreams?
*number*
What is your name?
*name*
What is your dream?
*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.
uj5u.com熱心網友回復:
當您使用 讀取$dreams陣列中的值時foreach ($dreams as $key => $value),您期望名稱作為鍵,但這不是您插入值的方式。您可以將名稱用作陣列鍵,如下所示:
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/447381.html
