[英]Array key name mapping in PHP
I am really getting stuck in renaming an array using a mapping array in PHP.我真的陷入了在 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;
}
Try this:尝试这个:
foreach ($source as $k=>$v) {
if(!is_array($post[$k]))
$ret[$v['keys'][0]] = $post[$k];
else {
foreach($v as $kk=>$vv)
$ret[$vv['keys'][0]][$vv['keys'][1]] = $post[$k][$kk];
}
}
print_r($ret);
The final output of this will be stored in $ret
.最终输出将存储在
$ret
。
Variables that I'll use bellow:我将在下面使用的变量:
$k
- will refer to the key of $source
in the current iteration $k
- 将引用当前迭代中$source
的键$v
- will refer to the array associated at $source[$k]
$v
- 将引用与$source[$k]
关联的数组$kk
- will refer to the key of $v
in the current iteration $kk
- 将引用当前迭代中$v
的键$vv
- will refer to the array associated at $v[$kk]
$vv
- 将引用与$v[$kk]
关联的数组Firstly, we loop over the elements of $source
.首先,我们遍历
$source
的元素。 Inside we have two options:在里面我们有两个选择:
$post[$k]
holds value(not array). $post[$k]
保存值(不是数组)。 In this case, we build an element for $ret
.$ret
构建一个元素。 The key will use $v['keys'][0]
(the first element of the keys
array in $v
).$v['keys'][0]
( $v
中的keys
数组的第一个元素)。 The value will use the data from $post[$k]
.$post[$k]
。$post[$k]
is an array. $post[$k]
是一个数组。 In this case we will iterate over $v
.$v
。 In each iteration we build an array element for $ret
.$ret
构建一个数组元素。 The array key will be $vv['keys'][0]
(the first element of the keys
array of $vv
. The element of $vv['keys'][0]
will have a key that will be $vv['keys'][1]
(the second element of keys
array of $vv
). The value for $vv['keys'][1]
will be $post[$k][$kk]
.$vv['keys'][0]
( $vv
的keys
数组的第一个元素。 $vv['keys'][0]
的元素将有一个键$vv['keys'][1]
( $vv
的keys
数组的第二个元素) $vv['keys'][1]
将是$post[$k][$kk]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.