PHP foreach循环自动添加变量

时间:2013-03-08 07:12:28

标签: php arrays loops foreach

我有一个PHP循环,似乎是以某种方式添加或存储数据,这是不相关的,并且从它解释的数组的最后一个值开始,然后回想起来有点混乱。这是我的代码:

$filenamewithext = explode("\n", $_POST['filename']);
foreach($filenamewithext as $line)
{   
    $filename = mysql_real_escape_string($line);
    $fileletter = substr($filename, 0, 1);
        if (ctype_alpha($fileletter)) {
            $folder = $folder.$fileletter."/";
        } else {
            $folder = $folder. "0-9" . "/";
        }   
    echo $folder;

}

它输出类似这样的东西,因为我们有$ filenamewithtext = test1,test2和test3基于POST数据是什么是HTML文本区域,并创建一个数组,每个新行都是一个新值。

输出:

  

/文件夹名/吨// FOLDERNAME / T / T / FOLDERNAME / T / T / T /

我需要的是每次只有1“t”而不是每次重复的第一个字符。我一直试图解决这个问题已经有一段时间了,任何帮助都会受到赞赏。感谢。

更新:

用于启动$ folder变量的代码。

if (array_key_exists('submit', $_POST)) {
$cat = $_POST['selectCat'];
switch ($cat){
    case "Adult" : 
        $tablename = "voxadultfilestable" ;
        $folder = "/imagesxxx/" ;
        break;
    case "clips" : 
        $tablename = "voxfilestable";
        $folder = "/images/" ;
        break;
    case "concerts" :
        $tablename = "voxconcertsfilestable";
        $folder = "/imagesconcerts/" ;          
        break;
    case "mixes" : 
        $tablename = "voxmixesfilestable";
        $folder = "/imagesmixes/"   ;       
        break;
    case "movies" : 
        $tablename = "voxmoviesfilestable";
        $folder = "/imagesmovies/"  ;
        break;
    case "mp3" : 
        $tablename = "voxmp3filestable";
        $folder = "/imagesmp3/" ;
        break;
}

2 个答案:

答案 0 :(得分:0)

我认为问题是因为你的foreach循环遍历变量并声明一个具有相同名称的变量:

foreach($filenamewithext as $filenamewithext)

将其更改为

foreach($filenamewithext as $fext) {
}

修改,$filename1$folder是什么?您继续追加$folder。将它重置在循环的顶部。

答案 1 :(得分:0)

尝试添加

$folder = '';

在foreach循环内部启动。它看起来

$ folder = $ folder。$ fileletter。“/”; 正在添加旧的$文件夹并返回$ folder

试试吧

$filenamewithext = explode("\n", $_POST['filename']);
foreach($filenamewithext as $line)
{   
    $folder = ''; // empty $folder at beginning of loop
    $filename = mysql_real_escape_string($line);
    $fileletter = substr($filename, 0, 1);
        if (ctype_alpha($fileletter)) {
            $folder = $folder.$fileletter."/";
        } else {
            $folder = $folder. "0-9" . "/";
        }   
    echo $folder;

}