get the sub index in foreach loop in simpleXMLElement(在 simpleXMLElement 的 foreach 循环中获取子索引)
本文介绍了在 simpleXMLElement 的 foreach 循环中获取子索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的php代码:
HTML;}?>
php 渲染页面后, 返回 .我想要 $key 获取其中的数量,那么如何获得?
解决方案
这是因为 simpleXML 结构不是普通的数组,而是没有数组索引的迭代器.
除了使用变量手动跟踪之外,我不知道还有其他解决方案:
$index = 0;$xml = simplexml_load_file('post.xml');foreach($xml->item 作为 $item ){....$索引++;}<?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>
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>
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 ?
解决方案
This is because simpleXML structures are not normal arrays but iterators who do not have an array index.
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 循环中获取子索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在 simpleXMLElement 的 foreach 循环中获取子索引
基础教程推荐
猜你喜欢
- php中的foreach复选框POST 2021-01-01
- Web 服务器如何处理请求? 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的PDF导出 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
