2012-12-15 72 views
1

我這個XML的結構:的SimpleXML元素只提取第一個元素,但我需要的所有元素

<response status="success"> 
<campaign> 
<id>1</id> 
<nameCampaign>Raccolta Punti CCN</nameCampaign> 
<type>points</type> 
<balances> 
    <balance>10.00 </balance> 
    </balances> 
</campaign> 
<campaign> 
<id>6</id> 
<nameCampaign>Abbonamenti</nameCampaign> 
<type>subscription</type> 
    <balances> 
    <balance>6.00 Lampada solare</balance> 
    </balances> 
    <balances> 
    <balance>4.00 doccia solare</balance> 
    </balances> 
    <balances> 
    <balance>3.00 trifacciale</balance> 
    </balances> 
</campaign> 
</response> 

而且我需要數組轉換。

如果我使用

foreach($result->campaign as $bilancio) { 
    $balance[] = array ( 'nameCampaign' => (string)$bilancio->nameCampaign, 
          'balances'  => (string)$bilancio->balances->balance );  
} // foreach 

我得到這個數組

Array 
    (
[0] => Array 
    (
     [nameCampaign] => Raccolta Punti CCN 
     [balances] => 10.00 
    ) 

[1] => Array 
    (
     [nameCampaign] => Abbonamenti 
     [balances] => 6.00 Lampada solare 
    ) 
) 

你怎麼會注意到,ID 6有三個子節點(balances->平衡),而不是唯一的一個。我如何獲得一個完整的數組?

謝謝大家,祝你週末愉快!

回答

1

而不是閱讀(它總是會給你第一個元素只與simeplxml),你迭代所有元素與foreach

這裏有一個辦法:

$balance = array(); 
foreach ($result->campaign as $campaign) 
{ 
    $arr = array(); 
    foreach ($campaign->balances as $campaignBalance) 
    { 
     $arr[] = (string) $campaignBalance->balance; 
    } 

    $balance[] = array(
     'nameCampaign' => (string) $campaign->nameCampaign, 
     'balances'  => $arr 
    ); 
} 

print_r($balance); 

,這將給你這樣的結果:

Array 
(
    [0] => Array 
     (
      [nameCampaign] => Raccolta Punti CCN 
      [balances] => Array 
       (
        [0] => 10.00 
       ) 
     ) 
    [1] => Array 
     (
      [nameCampaign] => Abbonamenti 
      [balances] => Array 
       (
        [0] => 6.00 Lampada solare 
        [1] => 4.00 doccia solare 
        [2] => 3.00 trifacciale 
       ) 
     ) 
) 
+0

非常感謝您! – sineverba

+0

@Dale:我編輯了你的答案,'count()'是多餘的。 「foreach」可以做零,一個或多個元素。這是迭代的好處,不需要預先計數。 – hakre

+0

@hakre,不知道那個歡呼的傢伙 – Dale

相關問題