在simpleXMLElement的foreach循环中获取子索引 [英] get the sub index in foreach loop in simpleXMLElement

查看:179
本文介绍了在simpleXMLElement的foreach循环中获取子索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?xml version="1.0" encoding="utf-8"?>
<items>
  <item>
    <title>This is title1</title>
    <desc>This is desc1</desc>
    <image></image>
    <tudou></tudou>
  </item>
  <item>
    <title>This is title2</title>
    <desc>This is desc2</desc>
    <tudou>55362137</tudou>
  </item>
  <item>
    <title>This is title3</title>
    <desc>This is desc4</desc>
  </item>
</items>

这里是我的php代码:

here's my php code:

<div class="nav">
    <ul>
        <?php
                $xml = simplexml_load_file('post.xml');
                //print_r($xml);
                foreach($xml->item as $key=>$item )
                {
                    echo <<<HTML
                    <li>
                    <div class="published">
                        <span class="day">13</span>
                        Sep 2010
                    </div>

                    <div class="summary">
                    <a href="#slide-$key">
                            <h3>$item->title</h3>
                    </a>
                    </div>
                    </li>

HTML;
                }
            ?>
        </ul>
    </div>

在php呈现页面之后,< a href =#slide - $ key> return < a href =#slide-item>
我想要$ key获得其中的数目,
所以如何获得?

after php render the page,the <a href="#slide-$key"> return <a href=#slide-item>. I want $key get the number of which , so how to get ?

推荐答案

因为simpleXML结构不是正常的数组,而是没有数组索引的迭代器。

This is because simpleXML structures are not normal arrays but iterators who do not have an array index.

我不知道使用变量手动跟踪任何其他解决方案: / p>

I don't know of any other solution than keeping track manually using a variable:

 $index = 0;
 $xml = simplexml_load_file('post.xml');

 foreach($xml->item as $item )
   {
       ....
       $index++;
    }

这篇关于在simpleXMLElement的foreach循环中获取子索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆