数组按键值更改结构

我的代码是:


$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 次。


千万里不及你
浏览 99回答 1
1回答

30秒到达战场

这是使您的代码按照您的意愿工作所需的修改$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 currenciesforeach($currencies as $currency) {&nbsp; $newArr[$currency['targetCurrency']] = $currency;}echo json_encode($newArr, JSON_PRETTY_PRINT);
打开App,查看更多内容
随时随地看视频慕课网APP