【发布时间】:2018-08-07 10:45:25
【问题描述】:
我真的陷入了使用 PHP 中的映射数组重命名数组的困境。我可以选择和更改具有字符串或 int 内容的元素的名称。但真的搞砸了嵌套数组。
映射数组:
$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']
]
);
改造前:
$post = array(
'id' => 1000,
'name' => 'API sample',
'proj' => array(
'general' => 10,
'category' => 50
)
);
期望的输出:
$result = array(
'app_id' => 1000,
'app_name' => 'API sample',
'project' => array(
'gen' => 10,
'cat' => 50
)
);
代码:
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;
}
【问题讨论】:
-
基于您的示例:
$result['project'][$source['proj']['general']['keys'][1]] = 10; -
这没有你想象的那么简单。你基本上需要一个 recursive 函数。向我们展示您迄今为止所做的尝试。
-
['app_name'], 'type' => 'int'],=>API sample是这个错误吗?