I am really getting stuck in renaming an array using a mapping array in PHP. I am able to pick and change the name of elements which has string or int content. But really getting messed up with a nested array.
Mapping array:
$source = array(
'id' => ['keys' => ['app_id'], 'type' => 'int'],
'name' => ['keys' => ['app_name'], 'type' => 'string'],
'proj' => [
'general' => ['keys' => ['project', 'gen'], 'type' => 'string'],
'category' => ['keys' => ['project', 'cat'], 'type' => 'string']
]
);
Before transforming:
$post = array(
'id' => 1000,
'name' => 'API sample',
'proj' => array(
'general' => 10,
'category' => 50
)
);
Desired output:
$result = array(
'app_id' => 1000,
'app_name' => 'API sample',
'project' => array(
'gen' => 10,
'cat' => 50
)
);
Code:
function renameArray($mappings,$inputObjectDb) {
$inputObjectDb = (array)$inputObjectDb;
$response = [];
foreach($mappings as $key => $mapping) {
//call itself in order to prepare sub array
if(!isset($mapping['keys'])) {
$response[$key] = prepareOutputData($mapping,$inputObjectDb);
} else {
$dbSubarray = $inputObjectDb;
foreach( $mapping['keys'] as $subkey) {
$response[$key] = $dbSubarray[$subkey];
$dbSubarray = &$dbSubarray[$subkey];
}
}
}
return $response;
}