将输入数组转换为另一个数组

时间:2017-07-03 13:42:20

标签: php arrays

我想要实现的是获取此输入数组:

$input = [
    "AccountId" => "18",
    "Id" => "53600065",
    "Name" => "Awesome Test Company From SS",
    "Financial" => [
         "vat" => "12345",
    ]
]

变成了这样的输出数组:

$output = [
    "account_id" => "18",
    "master_id" => "53600065",
    "name" => "Awesome Test Company From SS",
    "financial_data" => [
         "vat_number" => "12345"
    ]

]

输入可以包含一个或多个需要映射的字段。所以它也很容易看起来像这样:

$input2 = [
    "AccountId" => "18",
    "Street" => "Some Street 123",
    "Country" => "England",
    "Contacts" => [
       [
          "Id" => "1234",
          "Name" => "John Doe",
       ]
    ]
]

输出看起来像这样:

$output2 = [
    "account_id" => "18",
    "street_name" => "Some Street 123",
    "country" => "England",
    "contacts" => [
       [
          "contact_id" => "1234",
          "name" => "John Doe",
       ]
    ]
]

所以基本上我想将键从一个数组映射到另一个数组。输入可以具有比上面所示更多的键,并且可以具有嵌套数组作为值。 我也知道我需要支持的所有输入键,但不保证它们在每个请求中都是输入数组的一部分。

我天真的解决方案是建立一个像这样的数组

$result = [];
if (array_key_exists('AccountId', $input) {
    $result = array_merge($result, ['account_id' => $input['AccountId']]);
}
if (array_key_exists('Id', $input) {
    $result = array_merge($result, ['master_id' => $input['Id']]);
}
...

但是这很快变得混乱,它不灵活,只是看起来很糟糕。但是我怎样才能做到这一点呢?基本上我需要映射一些值['AccountId' => 'account_id', 'Id' => 'master_id'],但我似乎无法弄清楚如何正确地做到这一点。我希望能够递归遍历数组,然后映射值,但是如果输出数组的结构与输入的结构不同,并且键需要新名称,我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用array_intersect_keyarray_combine函数的解决方案:

$keys_map = [
    'AccountId' => 'account_id',
    'Id' => 'master_id',
    'Name' => 'name'
];
$intersection = array_intersect_key($input, $keys_map);
$result = [];

if (count($intersection) == count($keys_map)) {  // if all keys from $keys_map were matched
    $result = array_combine($keys_map, $intersection);
}

print_r($result);

输出:

Array
(
    [account_id] => 18
    [master_id] => 53600065
    [name] => Awesome Test Company From SS
)

http://php.net/manual/en/function.array-intersect-key.php