重新排序阵列属性然后再保存到PHP的XML [英] reordering array attributes then save back to XML in php

查看:112
本文介绍了重新排序阵列属性然后再保存到PHP的XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的XML:

  <picture id="2">
    <title>B</title>
  </picture>
  <picture id="3">
    <title>C</title>
  </picture>
  <picture id="0">
    <title>A</title>
  </picture>

努力实现这一点:

Trying to achieve this:

  <picture id="1">
    <title>B</title>
  </picture>
  <picture id="2">
    <title>C</title>
  </picture>
  <picture id="0">
    <title>A</title>
  </picture>

使用该得到的id属性值的列表:

Using this to get a list of 'id' attribute values:

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$picture = $objXML->xpath('picture');
$arrayCurrent = array();
foreach($picture as $value) {
    $arrayCurrent[] = (string)$value['id'];
}
sort($arrayCurrent); // put XML into numerical 'id' order
print_r($arrayCurrent);

它返回:阵列([0] => 0 [1] => 2 [2] => 3)
任何想法如何重新建立索引像这样:0,1,2并保存相应的'ID'在XML文档属性回到正确的位置。

It returns: Array ( [0] => 0 [1] => 2 [2] => 3 ) Any ideas how to re-index like so: 0, 1, 2 and save the appropriate 'id' attributes back to their correct positions in the XML doc?

谢谢,安迪

推荐答案

数字ID为了保持并取得连续的:

Numerical id order is maintained and made consecutive:

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$picture = $objXML->xpath('picture');
usort($picture, create_function('$a,$b', 'return (string)$a["id"] - (string)$b["id"];'));
foreach ($pictures as $index => $node) $node["id"] = $index;

这篇关于重新排序阵列属性然后再保存到PHP的XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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