PHP - For循环只返回数组中的最后一个变量

时间:2010-01-06 09:34:17

标签: php arrays loops for-loop

我有一个奇怪的问题,PHP中的for循环只返回数组中的最后一项。

使用SimpleXML从XML文件创建数组。

代码应该返回:

<tags><tag value="Tag1" /><tag value="Tag2" /><tag value="Tag3" /></tags>

但我只是得到:

<tags><tag value="Tag3" /></tags>

所以它忽略了数组中的最后一项,无论我在那里有多少。

谁能看到我做错了什么?

以下是代码:

<?php

function gettags($xml)
{
    $xmltags = $xml->xpath('//var[@name="infocodes"]/string');
    return $xmltags[0];
}

//Path to the XML files on the server
$path = "/xmlfiles/";

//Create an array with all the XML files
$files = glob("$path/*.xml");

foreach($files as $file)
{
    $xml = simplexml_load_file($file);
    $xmltags = gettags($xml);

//Using the , character split the values coming from the $xmltags into an array
$rawtags = explode(',', $xmltags);

//Loop through the tags and add to a variable. Each tag will be inside an XML element - <tag value="tagname" />
for ($i = 0; $i <count($rawtags); $i++){
    $tags = '<tag value="' . $rawtags[$i] . '" />';
}

//Replace HTML escaped characters (ä, å, ö, Å, Ä, Ö) and the | character with normal characters in the tags variable
$tagsunwantedchars = array("&Ouml;", "&Auml;", "&Aring;", "&ouml;", "&auml;", "&aring;", "|");
$tagsreplacewith = array("Ö", "Ä", "Å", "ö", "ä", "å", " - ");
$tagsclean = str_replace($tagsunwantedchars, $tagsreplacewith, $tags);

//Create the full tag list and store in a variable
$taglist = "<tags>$tagsclean</tags>";

}

echo $taglist;

?>

这是XML文件:

<wddxPacket version='1.0'>
    <header/>
    <data>
        <struct>
            <var name='infocodes'>
                <string>Tag1,Tag2,Tag3</string>
            </var>
        </struct>
    </data>
</wddxPacket>

3 个答案:

答案 0 :(得分:12)

简单的错误:在循环中使用$tags .=而不是$tags =

$tags = '';
for ($i = 0; $i <count($rawtags); $i++){
    $tags .= '<tag value="' . $rawtags[$i] . '" />';
}

答案 1 :(得分:2)

for ($i = 0; $i <count($rawtags); $i++){
    $tags = '<tag value="' . $rawtags[$i] . '" />';
}

您只是在每次迭代时覆盖$tags变量。尝试:

$tags = '';
foreach ($rawtags as $rawtag) {
    $tags .= '<tag value="' . $rawtag . '" />';
}

请注意,您应该在附加$tags之前对其进行初始化(否则会生成PHP警告)。

此外,使用foreach代替for循环可使您的代码更简单,更易读。当没有被噪声包围时,这样的琐碎错误更容易被发现。

答案 2 :(得分:0)

$tags .= '<tag value="' . $rawtags[$i] . '" />';

这可以解决您的问题。

相关问题