我的代码是:
$xml = simplexml_load_file('http://www.floatrates.com/daily/gel.xml');
$cur = array($xml);
$array = json_decode(json_encode($cur), true);
$newArr = [];
foreach ($array as $value) {
foreach($value['item'] as $key){
array_push($newArr, [ $key['targetCurrency'] => $key ]);
print '<pre>'; print_r($newArr); print '</pre>';
}
}
输出为https://prnt.sc/terpnc
我需要让它像这个例子:
[USD] => Array
(
[title] => 1 GEL = 0.32613048 USD
[link] => http://www.floatrates.com/gel/usd/
[description] => 1 Georgian lari = 0.32613048 U.S. Dollar
[pubDate] => Thu, 9 Jul 2020 12:00:01 GMT
[baseCurrency] => GEL
[baseName] => Georgian lari
[targetCurrency] => USD
[targetName] => U.S. Dollar
[exchangeRate] => 0.32613048
[inverseRate] => 3.06625741
[inverseDescription] => 1 U.S. Dollar = 3.06625741 Georgian lari
)
[EUR] => Array
(
[title] => 1 GEL = 0.28808543 EUR
[link] => http://www.floatrates.com/gel/eur/
[description] => 1 Georgian lari = 0.28808543 Euro
[pubDate] => Thu, 9 Jul 2020 12:00:01 GMT
[baseCurrency] => GEL
[baseName] => Georgian lari
[targetCurrency] => EUR
[targetName] => Euro
[exchangeRate] => 0.28808543
[inverseRate] => 3.47119257
[inverseDescription] => 1 Euro = 3.47119257 Georgian lari
)
我怎样才能像在例子中那样做呢? 顺便说一下,在我的代码中,我多次获得相同的值,例如,您可以看到[USD]=>; 数组149倍。。
以下是使代码按您所希望的方式工作所需的修改
$xml = simplexml_load_file('http://www.floatrates.com/daily/gel.xml');
$cur = array($xml);
$array = json_decode(json_encode($cur), true);
$newArr = [];
$currencies = $array[0]['item']; // here are your currencies
foreach($currencies as $currency) {
$newArr[$currency['targetCurrency']] = $currency;
}
echo json_encode($newArr, JSON_PRETTY_PRINT);