What i'm trying to achieve is to get this input array:
$input = [
"AccountId" => "18",
"Id" => "53600065",
"Name" => "Awesome Test Company From SS",
"Financial" => [
"vat" => "12345",
]
]
Turned into something like this output array:
$output = [
"account_id" => "18",
"master_id" => "53600065",
"name" => "Awesome Test Company From SS",
"financial_data" => [
"vat_number" => "12345"
]
]
The input can have one or more fields that needs to be mapped. So it could easily look like this as well:
$input2 = [
"AccountId" => "18",
"Street" => "Some Street 123",
"Country" => "England",
"Contacts" => [
[
"Id" => "1234",
"Name" => "John Doe",
]
]
]
And have output looking like this:
$output2 = [
"account_id" => "18",
"street_name" => "Some Street 123",
"country" => "England",
"contacts" => [
[
"contact_id" => "1234",
"name" => "John Doe",
]
]
]
So basically I want to map the keys from one array to another. The input can have more keys than shown above, and can have nested arrays as values. I also know all the input keys I need to supports, but they are not guaranteed to be part of the input array on every request.
My naive solution is to build an array like this
$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']]);
}
...
But this becomes messy really quick, it's not flexible, and in simply just looks bad. But how can I achieve this in a good matter? Basically I need to map some values ['AccountId' => 'account_id', 'Id' => 'master_id']
, but I can't seem to figure out how to do this properly. I would love to be able to traverse the array recursively, and then map the values, but how can I do this, if the structure of the output array is not necceseraly the same as the input, and the keys needs new names?