1

我有这个 XML 结构:

<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 有三个子节点(余额->余额),而不仅仅是一个。我怎样才能获得一个完整的数组?

谢谢大家,周末愉快!

4

1 回答 1

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
                )
        )
)
于 2012-12-15T14:12:37.120 回答