如何在我的多维关联数组中回显正确的键?
How can I echo the right key in my multidimensional associative array?
我的objective是创建一个多维关联数组,里面有朋友和他们的梦想(用户输入)。我认为(希望)我可以接近完成它,但是在回应最后一步时我得到了一个不需要的结果:
我试图在第 22 行回显包含 'friend' 名称的句子。结果我得到的不是用户输入的名称,而是 'Array'。例:Array的梦想是:攀登珠穆朗玛峰
有谁知道我怎么知道这里朋友的名字的?
A line/string 应该为每个填写的单独梦想回显。为了清楚起见,我包括了打印功能,稍后将删除。谢谢!
<?php
$friends = readline('How many friends should we ask for their dreams? ');
$array = [];
if (is_numeric($friends) == false) {
exit("This is not a number." . PHP_EOL);
} else if ($friends == 0) {
exit("This is not valid input." . PHP_EOL);
} else {
for ($i = 1; $i <= $friends; $i++) {
$name_key = readline('What is your name? ');
$number_dreams = readline('How many dreams are you going to enter? ');
for ($x = 1; $x <= $number_dreams; $x++) {
$dream_value = readline('What is your dream? ');
$array[$name_key][] = $dream_value;
}
print_r($array);
}
foreach ($array as $friend) {
foreach ($friend as $key => $value) {
echo $friend . ' has this as their dream: ' . $value . PHP_EOL;
}
}
}
组装 $array 后试试这个:
foreach ($array as $frndNm=>$dreams){
foreach($dreams as $dream){
echo( $frndNm.' dream is '.$dream);
}
}
我的objective是创建一个多维关联数组,里面有朋友和他们的梦想(用户输入)。我认为(希望)我可以接近完成它,但是在回应最后一步时我得到了一个不需要的结果:
我试图在第 22 行回显包含 'friend' 名称的句子。结果我得到的不是用户输入的名称,而是 'Array'。例:Array的梦想是:攀登珠穆朗玛峰
有谁知道我怎么知道这里朋友的名字的?
A line/string 应该为每个填写的单独梦想回显。为了清楚起见,我包括了打印功能,稍后将删除。谢谢!
<?php
$friends = readline('How many friends should we ask for their dreams? ');
$array = [];
if (is_numeric($friends) == false) {
exit("This is not a number." . PHP_EOL);
} else if ($friends == 0) {
exit("This is not valid input." . PHP_EOL);
} else {
for ($i = 1; $i <= $friends; $i++) {
$name_key = readline('What is your name? ');
$number_dreams = readline('How many dreams are you going to enter? ');
for ($x = 1; $x <= $number_dreams; $x++) {
$dream_value = readline('What is your dream? ');
$array[$name_key][] = $dream_value;
}
print_r($array);
}
foreach ($array as $friend) {
foreach ($friend as $key => $value) {
echo $friend . ' has this as their dream: ' . $value . PHP_EOL;
}
}
}
组装 $array 后试试这个:
foreach ($array as $frndNm=>$dreams){
foreach($dreams as $dream){
echo( $frndNm.' dream is '.$dream);
}
}