我有这种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有三个子节点(balances-&gt; balance)而不仅仅是一个。我怎么能得到一个完整的阵列?
谢谢大家,祝周末愉快!
答案 0 :(得分:1)
您可以使用foreach
迭代所有元素,而不是阅读(只会使用simeplxml为您提供第一个元素)。
这是一种方式:
$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
)
)
)