简体   繁体   English

PHP访问SimpleXMLElement对象数组键

[英]PHP Accessing SimpleXMLElement Object array keys

In the following SimpleXMLElement Object $results , I would like to remove the element with ID 13011146 from the TEST array. 在下面的SimpleXMLElement对象$results ,我想从TEST数组中删除ID为13011146的元素。 I'm not sure how to properly access the array key with value 1 , so I'm using a counter $i , but that gives me an error Node no longer exists , pointing to the foreach line. 我不确定如何正确地访问值为1的数组键,所以我使用了计数器$i ,但这给我一个错误Node no longer exists ,指向foreach行。

TL;DR : How do you unset $result->TEST[1] ? TL; DR :如何取消设置$result->TEST[1]

SimpleXMLElement Object
(
    [TEST] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [ID] => 13011145
                        )

                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [ID] => 13011146
                        )

                )
        )

)

PHP: PHP:

$i = 0;
foreach($results->TEST as $key => $value) {
    if( (string)$value['ID'] == 13011146 ) {
        unset($results->TEST[$i]);
    }
    $i++;
}

a more elegant way; 更优雅的方式 it gives you the same results without using $attributes[ '@attributes' ] : 它不使用$ attributes ['@attributes']即可提供相同的结果:

$attributes = current($element->attributes());

For specific key/value pair, we can use like: 对于特定的键/值对,我们可以这样使用:

$attributes = current($value->attributes()->NAME);

Hope it helps ! 希望能帮助到你 !

Try this: 尝试这个:

   $sxe = new SimpleXMLElement($xml);
   foreach ($sxe->children() as $child){
      foreach($child as $key=>$item){
         echo $key.': '.$item.'<br />';
      }
   }
foreach($results->TEST->children() as $key => $value) { 
    $attributes = $value->attributes();
    foreach($attributes as $a => $b) {
        if (( (string)$a == 'ID' ) && ( (string)$b == '13011146' )) {    
            unset($results->TEST[$key]);    
        }
    }
}

try this 尝试这个

$node = $results->children();
unset($node[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM