将平面数组转换为分层多维数组
我有一个带有键值对的标准数组 - 我想使用键将其转换为多维数组。困难似乎在于我需要递归循环未知数量的新键并将它们转换为多维数组。简而言之,我想要这个:
$val[alfa.xray.uno] = "Some value";
=> $val['alfa']['xray']['uno'] = "Some value";
示例: (代码失败并且还需要处理 N 维 - 但你明白了..)
$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 可以解决问题吗?
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";
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;
}
Perhaps RecursiveArrayIterator will do the trick?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用引用来连续迭代并构建嵌套数组结构:
You could use references to successively iterate through and build up the nested array structure:
使用递归卢克
use the recursion Luke
您可以在遍历数组层次结构级别时使用 引用:
You can use a reference while walking though the array hierarchy levels: