Php多维数组与混合for和Foreach循环

问题描述 投票:0回答:2

我是PHP的初学者,目前正致力于将经典ASP(VB)的小型网站重新编码为PHP,我想知道是否有一个相当直接的“翻译”将这个概念从一种语言转换为另一种语言?

我知道嵌套的foreach循环可以完成这项工作,但是,我很好奇,如果一个for fore循环,带有foreach内循环可以工作吗?

这是我试图做的事情。由于某种原因,变量$ strMonth_Alpha不会返回。感谢任何线索。

PHP代码:

$strMonthList='01,January;02,February;03,March;04,April;05,May;06,June;07,July;08,August;09,September;10,October;11,November;12,December';
$arrMonthList=explode(';',$strMonthList); //create the outer array
    //print_r(array_values($arrMonthList));
    for ($ii=0; $ii<count($arrMonthList); $ii++) {
        $M=explode(',',$arrMonthList[$ii]); //create the inner array
        //print_r(array_values($M));
        $myArrayCount=0;
            foreach($M as $a => $item) {
                    if ($myArrayCount==0) {
                    $strMonth_Num=$M[$myArrayCount];
                    //echo '<BR>$strMonth_Num...'.$strMonth_Num.'<BR>';
                    }

                    if ($myArrayCount==1) {
                    $strMonth_Alpha=$M[$myArrayCount];
                    }else{
                    $strMonth_Alpha='';
            $myArrayCount=($myArrayCount+1);
                 }  
            }
    }//to next month
php arrays for-loop multidimensional-array nested
2个回答
1
投票

尝试了你的代码,除了格式化之外什么也没有改变,只是回显变量,我得到值“十二月”。这是你想要的吗 ?

只需在最后一个括号后添加到代码的末尾即可。

echo $strMonth_Alpha;

1
投票

代码中的print($strMonth_Alpha)或打印任何其他变量来调试并查看事情的变化。我刚刚尝试在if / else语句后打印这个,我得到:

print($strMonth_Alpha . '<br/>');

January
February
March
April
May
June
July
August
September
October
November
December

知道你每个循环覆盖$strMonth_Alpha

如果像01,January这样的数据总是采用这种格式(即假设您的代码可以安全地生成),那么您可以简化代码以删除第二个for循环。

$arrMonthList=explode(';',$strMonthList); //create the outer array
//print_r(array_values($arrMonthList));
for ($ii=0; $ii<count($arrMonthList); $ii++) {
    $M=explode(',',$arrMonthList[$ii]); //create the inner array
    echo($M[0] . "<br/>"); // num
    echo($M[1] . "<br/>"); // month name

}//to next month
© www.soinside.com 2019 - 2024. All rights reserved.