Php 如何访问foreach中的特定关联数组?
如何访问Php 如何访问foreach中的特定关联数组?,php,arrays,foreach,Php,Arrays,Foreach,如何访问foreach循环中的特定关联数组? 例如,我想显示以下文本:“如果现在第一个日期表示现在是一月” 以下是我到目前为止的情况: $namemonth = array( 1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May", 6 => "June", 7 => "July", 8
foreach
循环中的特定关联数组?
例如,我想显示以下文本:“如果现在第一个日期表示现在是一月”
以下是我到目前为止的情况:
$namemonth = array(
1 => "January",
2 => "February",
3 => "March",
4 => "April",
5 => "May",
6 => "June",
7 => "July",
8 => "August",
9 => "September",
10 => "October",
11 => "November",
12 => "December"
);
foreach ($namemonth as $key => $value) {
echo "if now the $key[1] date, that's means now the month of $value[1]";
}
但当我尝试运行代码时,浏览器中会显示以下值:
如果现在是日期,则表示现在是a月。到12月*
您不需要传递索引来显示值。只需直接回显
$key
和$value
foreach ($namemonth as $key => $value)
{echo "if now the $key date, that's means now the month of $value <br>";}
foreach($namemonth作为$key=>$value)
{echo“如果现在是$key日期,则表示现在是$value的月份
”;}
要解释你做错了什么,让我们浏览一下你提供的代码:
首先,您的foreach
循环:
foreach ($namemonth as $key => $value)
是$namemonth
数组
是$key
数组的当前索引,例如
$namemount[1]、$namemount[2]、…
是当前$value
索引的值数组
$key[1]
转换为1[1],2[1],3[1]…
$value[1]
转换为一月[1]、二月[1]、三月[1]…
正如您所看到的,您试图获取的值是错误的<代码>1[1]不存在,一月[1]也不存在
如果您真的只想打印1月份,请执行以下操作:
foreach ($namemonth as $key => $value)
{
if($key == 1)
{
echo "if now the $key date means now the month of $value<br/>";
// Use break to quit the foreach loop after `if` statement is true
break;
}
}
// Output
if now the 1 date means now the month of January
foreach($namemonth作为$key=>$value)
{
如果($key==1)
{
echo“如果现在$key日期表示现在$value的月份
”;
//在'if'语句为true后,使用break退出foreach循环
打破
}
}
//输出
如果现在的1日期表示现在的1月份
你应该试试这个
$month_names = array(
1 => "January",
2 => "February",
3 => "March",
4 => "April",
5 => "May",
6 => "June",
7 => "July",
8 => "August",
9 => "September",
10=> "October",
11=> "November",
12=> "December"
);
// Here $month_names is an array.
foreach($month_names AS $month_number => $month_name){
// Here $month_number is a key of an array.
// Here $month_name is a value of an array.
echo "if now the $month_number date, that's means now the month of $month_name <br/>";
}
$month\u names=数组(
1=>“一月”,
2=>“二月”,
3=>“三月”,
4=>“四月”,
5=>“五月”,
6=>“六月”,
7=>“七月”,
8=>“八月”,
9=>“九月”,
10=>“十月”,
11=>“11月”,
12=>“12月”
);
//这里$month\u names是一个数组。
foreach($month\u name作为$month\u number=>$month\u name){
//这里$month_number是数组的键。
//这里$month\u name是数组的值。
echo“如果现在是$month_number日期,则表示现在是$month_name的月份
”;
}
输出
如果现在是1号,那就意味着现在是1月
如果现在是2号,那就意味着现在是2月
如果现在是3号,那意味着现在是3月
如果现在是4号,那意味着现在是4月
如果现在是5号,那意味着现在是5月
如果现在是6号,那意味着现在是6月
如果现在是7号,那意味着现在是7月
如果现在是8号,那意味着现在是8月
如果现在是9号,那意味着现在是9月
如果现在是10号,那就意味着现在是10月
如果现在是11号,那意味着现在是11月
如果现在是12日,这意味着现在是12月份只使用$key和$value,而不是$key[1]$value[1]谢谢给出的答案,但我只想显示key($1)和value($1)。你能帮我吗?所以你不需要显示2月到12月的值?非常感谢你真的帮了我大忙,现在我不能显示输出;**如果现在的1日期表示现在的1月份**