【问题标题】:re-index array attribute id's then save to XML in php [duplicate]重新索引数组属性ID,然后在php中保存到XML [重复]
【发布时间】:2010-11-11 19:01:49
【问题描述】:

可能的重复:
reordering array attributes then save back to XML in php
php loop not working as expected

我有这个 XML:

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

试图实现这个 XML:

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

使用它来获取“id”属性值列表:

$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);

它返回: Array ( [0] => 0 [1] => 2 [2] => 3 ) 任何想法如何像这样重新索引:0、1、2 并保存适当的 'id' 属性回到它们在 XML 文档中的正确位置?

谢谢,安迪

【问题讨论】:

  • 抱歉,直到现在我才意识到我被允许/应该选择答案。感谢您指出这一点,我现在已经接受了对我帮助最大的答案。
  • 好的,我不确定您要使用什么规则进行排序...我的意思是,一般规则。您所需的 XML 没有按数字顺序排列的 id。数字顺序为 0 1 2,并且您写道希望您的 XML id 顺序为 1 2 0。
  • 这几乎是同一作者提出的至少两个问题的重复。 =\

标签: php xml arrays simplexml


【解决方案1】:
<?
$rtn = $refer = array();
foreach($picture as $value)
{
  $id = (int) $value->attributes()->id;
  $refer[$id] = array('id'=>$id, 'title'=>(string) $value->title);
}
$xml = simplexml_load_string('<test/>');
ksort($refer);
foreach ($refer as $idx=>$arr)
{
  $node = $xml->addChild('picture');
  $node->addAttribute('id', $arr['id']);
  $node->addChild('title', htmlentities($arr['title']));
}
echo $xml->asXml();
?>

【讨论】:

  • 感谢您的回复,我尝试使用它,但无法正常工作。鉴于对我有用,我将发布另一个解决方案。
【解决方案2】:

数字ID顺序保持并连续:

$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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2012-08-16
    • 2018-02-07
    • 2017-09-13
    相关资源
    最近更新 更多