2012-01-05 50 views
1

次のSimpleXMLElementオブジェクト$resultsでは、ID 13011146の要素をTEST配列から削除したいと考えています。私は適切に値1の配列キーにアクセスする方法がわからないので、私はカウンタ$iを使用していますが、それはエラーNode no longer exists、foreach行を指しています。PHP SimpleXMLElementオブジェクト配列キーへのアクセス

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++; 
} 
+0

はあなたには、いくつかの理由で$キー== TEST – maxjackie

答えて

0
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]);  
     } 
    } 
} 
+0

は動作しませんメインため' XML'を提供することができ、あなたの構造を読み違え:修正する必要がありますchildren()の呼び出しによって編集されたバージョン – stef

+0

申し訳ありませんがために、 'のSimpleXMLElement Object' –

+0

を参照してください。最初のforeachループにはまだ入力しません。■children()を削除した場合、$ aと$ bで一致した場合は$ keyの値間違っている。 – stef

0

この

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

もっとエレガントな方法を試してみてください。それはあなたの$属性を使用せずに同じ結果[ '@attributes']得られます。特定のキー/値のペアのために

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

を、我々は次のように使用することができます:

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

はそれが役に立てば幸い!

0

これを試してみてください:

$sxe = new SimpleXMLElement($xml); 
    foreach ($sxe->children() as $child){ 
     foreach($child as $key=>$item){ 
     echo $key.': '.$item.'<br />'; 
     } 
    } 
関連する問題