为了账号安全,请及时绑定邮箱和手机立即绑定

数组按键值更改结构

数组按键值更改结构

PHP
千万里不及你 2023-07-21 16:08:48
我的代码是:$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 次。
查看完整描述

1 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

这是使您的代码按照您的意愿工作所需的修改


$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);


查看完整回答
反对 回复 2023-07-21
  • 1 回答
  • 0 关注
  • 98 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信