我有一系列的列表键,例如:
$list_map_key=[
['pn','pn1','pp','pp1'],
['pn','pn1','pp','pp2'],
['pn','pn2','pp','pp5'],
['pn','pn2'],
];
我想像这样构建映射键数组以替换(pp)的值
$data_return['pn']['pn1']['pp']['pp1']=3000;
$data_return['pn']['pn1']['pp']['pp2']=3000;
$data_return['pn']['pn2']['pp']['pp5']=3000;
$data_return['pn']['pn2']=3000;
但是数组$ data_return ['pn'] ['pn1'] ['pp'] ['pp1']的键必须从数组键列表中动态生成。
我想构建一些函数来从列表数组键调用位置数据,并添加,替换或删除数据。
答案 0 :(得分:1)
由于$data_return['pn']['pn2']
不能同时是数组和值,因此无法实现所需的确切输出。但是,您可以使用此代码实现类似的操作。函数push_value
使用一个键数组,并根据这些键将值推入多维数组。然后,我们通过遍历$data_return
中的每个单个值并使用$list_map_key
将各个数组合并在一起来生成array_merge_recursive
:
function push_value($keys, $value) {
$key = array_shift($keys);
if (count($keys)) {
return array($key => push_value($keys, $value));
}
else {
return array($key => $value);
}
}
$data_return = array();
$value = 3000;
foreach ($list_map_key as $keys) {
$data_return = array_merge_recursive($data_return, push_value($keys, $value));
}
print_r($data_return);
输出:
Array
(
[pn] => Array
(
[pn1] => Array
(
[pp] => Array
(
[pp1] => 3000
[pp2] => 3000
)
)
[pn2] => Array
(
[pp] => Array
(
[pp5] => 3000
)
[0] => 3000
)
)
)