[英]PHP Accessing SimpleXMLElement Object array keys
在下面的SimpleXMLElement對象$results
,我想從TEST數組中刪除ID為13011146
的元素。 我不確定如何正確地訪問值為1
的數組鍵,所以我使用了計數器$i
,但這給我一個錯誤Node no longer exists
,指向foreach行。
TL; DR :如何取消設置$result->TEST[1]
?
SimpleXMLElement Object
(
[TEST] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ID] => 13011145
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ID] => 13011146
)
)
)
)
PHP:
$i = 0;
foreach($results->TEST as $key => $value) {
if( (string)$value['ID'] == 13011146 ) {
unset($results->TEST[$i]);
}
$i++;
}
更優雅的方式 它不使用$ attributes ['@attributes']即可提供相同的結果:
$attributes = current($element->attributes());
對於特定的鍵/值對,我們可以這樣使用:
$attributes = current($value->attributes()->NAME);
希望能幫助到你 !
嘗試這個:
$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]);
}
}
}
嘗試這個
$node = $results->children();
unset($node[1]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.