如何使用循环数组

时间:2013-06-12 08:53:44

标签: php arrays loops

我有一个数组,它从xml文件中读取它的单元格,我是用“for”写的,但是现在因为我不知道我有多少节点我想用它开始的方式编写这个循环完成xml file.my代码的结尾是for:

$description=array();

for($i=0;$i<2;$i++)
{
$description[$i]=read_xml_node("dscription",$i);
}

和我的xml文件:

<eth0>
<description>WAN</description>      
</eth0>
<eth1>
<description>LAN</description>      
</eth1>

在这段代码中我必须知道“2”,但我想知道一种不需要知道“2”的方法。

3 个答案:

答案 0 :(得分:1)

我不确定你使用的是哪种解析器,但是使用simplexml非常容易,所以我使用simplexml将一些示例代码放在一起。

这样的事情应该可以解决问题:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<node>
<eth0>
<description>WAN</description>      
</eth0>
<eth1>
<description>LAN</description>      
</eth1>
</node>
XML;

$xml = new SimpleXMLElement($xmlstr);

foreach ($xml as $xmlnode) {
 foreach ($xmlnode as $description) {
  echo $description . " ";
 }
}

输出:

WAN LAN  

答案 1 :(得分:0)

$length = count($description);
for ($i = 0; $i < $length; $i++) {
  print $description[$i];
}

答案 2 :(得分:0)

您使用的解析器可能允许您使用while循环,当它到达XML文档的末尾时将返回false。例如:

while ($node = $xml->read_next_node($mydoc)) {
    //Do whatever...
}

如果不存在,您可以尝试使用count()作为for循环的第二个参数。它返回您指定的数组的长度。例如:

for ($i = 0; $i < count($myarray); $i++) {
    //Do whatever...
}