开发者

How to save pairs of data into an one array

I have XML file where I have name of currency and rate. I want to save those currencies and rate as pairs into an array, but it doesnt work, when I echo the array with foreach only last one appears. Here's my code:

<?php
$xml = simplexml_load_file("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
$array=array();
foreach ($xml->children() as $cubeMain) {
    foreach ($cubeMain->children() as $cubeTime) {
        echo "Kursid seisuga: " . $cubeTime['time'];
        foreach ($cubeTime->children() as $cubeCurr) {
            $currency=$cubeCurr['currency'];
            $rate=$cubeCurr['rate'];
            $array = array((strin开发者_运维知识库g)$currency => $rate);
            echo $currency . "&nbsp;" . $rate . "<br />";
        }
    }
}

foreach ($array as $currency => $rate){
    echo "$currency: $rate\n";
}

?>


try

$array[(string)$currency] = $rate;

instead of

$array = array((string)$currency => $rate);


If you expect to have several currency + rate couples, you'll want an array that contains sub-items, each one being made of currency + rate.

Typically, you'll first initialize your array :

$array = array();


Then, for each currency, you'll add an item into that array :

$array[] = array((string)$currency => $rate);

With that, you'll have a long list, but not indexed by currency -- which might not be that useful.

You'll probably, instead, prefer going with this second solution :

$array[(string)$currency] = $rate;

With that, your array will have the currency as key -- which make it much easier to find your data back, later.


Going with the second solution, your array is indexed by currency.

Which means you can find the rate for a specific currency this way :

echo $array['EUR'];  // if EUR is an exinsting currency

And loop over all data like this :

foreach ($array as $currency => $rate) {
    echo "$currency : $rate <br />";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜