PHP-用预定义的键列表替换数组键

时间:2018-10-04 04:51:19

标签: php arrays multidimensional-array key

我有一个多维数组,是在抓取网页后得到的。

Array
(
    [Dollar N. America] => Array
        (
            [Name] => Dollar N. America
            [Buy] => 3.311
            [Sell] => 3.314
        )

    [Yen Japan] => Array
        (
            [Name] => Yen Japan
            [Buy] => 0.028
            [Sell] => 0.033
        )

    [Euro Europe] => Array
        (
            [Name] => Euro Europe
            [Buy] => 3.752
            [Sell] => 3.948
        )
)

问题是我需要将数组键的名称更改为较短的名称:

[DollarUS] - [YenJP] - [EuroEU]

为了使它看起来像这样:

Array
(
    [DollarUS] => Array
        (
            [Name] => Dollar N. America
            [Buy] => 3.311
            [Sell] => 3.314
        )

    [YenJP] => Array
        (
            [Name] => Yen Japan
            [Buy] => 0.028
            [Sell] => 0.033
        )

    [EuroEU] => Array
        (
            [Name] => Euro Europe
            [Buy] => 3.752
            [Sell] => 3.948
        )
)

我尝试了几种方法,但没有找到结果:

foreach ($currency as $k => $v){
    $currency[$k]['DolarUS'] = $currency[$k]['Dollar N. America'];
    unset($monedas[$k]['Dollar N. America']);
}   

2 个答案:

答案 0 :(得分:1)

Promise

答案 1 :(得分:0)

您可以尝试array_combine():

http://php.net/manual/en/function.array-combine.php

$keys = ['DollarUS','YenJP','EuroEU'];
$values = [
    'Dollar N. America' => [
        'Name' => 'Dollar N. America'
        'Buy' => 3.311
        'Sell' => 3.314
    ],
    'Yen Japan' => [
        'Name' => 'Yen Japan'
        'Buy' => 0.028
        'Sell' => 0.033
    ],
    'Euro Europe' => [
        'Name' => 'Euro Europe'
        'Buy' => 3.752
        'Sell' => 3.948
    ]
];
$fixedKeys = array_combine($keys,$values);