变换平面阵列成分层,多维数组 [英] Transform flat array into a hierarchical, multi-dimensional array
本文介绍了变换平面阵列成分层,多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个标准的数组key-value对 - 我想用钥匙将其改造成一个多维数组。困难似乎是我需要循环递归新的密钥的数目不详,把它们变成一个多维数组。总之,我想这样的:
I have a standard array with key-value pairs - and I want to use the keys to transform it into a multi-dimensional array. The difficulty seems to be that I need to loop recursively the unknown number of new keys and turn them into a multi-dimensional array. In short, I want this:
$val[alfa.xray.uno] = "Some value";
=> $val['alfa']['xray']['uno'] = "Some value";
例如:
(在code失败,还需要处理N维 - 但你的想法。)
Example: (The code fails and also needs to handle N dimensions - but you get the idea..)
$arr['alfa.xray.uno'] = "Alfa X-Ray Uno";
$arr['alfa.yaho.duo'] = "Alfa Yaho Duo";
$arr['beta.xray.uno'] = "Beta X-Ray Uno";
$arr['beta.xray.duo'] = "Beta X-Ray Duo";
$arr['just-me'] = "Root-level item";
print_r( array_flat_to_multidimensional($arr) );
function array_flat_to_multidimensional($arr) {
foreach($arr as $key=>$val) {
$key = explode(".",$key);
for($i=0; $i<count($key); $i++) {
if($i==0) { $out[$key[$i]] = $val; }
else if($i==1) { $out[$key[$i-1]][$key[$i]] = $val; }
else if($i==2) { $out[$key[$i-2]][$key[$i-1]][$key[$i]] = $val; }
else if($i==3) { $out[$key[$i-3]][$key[$i-2]][$key[$i-1]][$key[$i]] = $val; }
}
}
return $out;
}
RecursiveArrayIterator 会做的伎俩?
推荐答案
您可以使用引用先后遍历并建立嵌套阵列结构:
You could use references to successively iterate through and build up the nested array structure:
$out = array();
foreach ($arr as $key=>$val) {
$r = & $out;
foreach (explode(".", $key) as $key) {
if (!isset($r[$key])) {
$r[$key] = array();
}
$r = & $r[$key];
}
$r = $val;
}
return $out;
这篇关于变换平面阵列成分层,多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文