正如示例中的标题所示,我需要一个平面数组,以便每个后面的键都是先前的值.
例:
array("I", "need", "this", "to", "be", "nested");
// To:
array("I" => array("need" => array("this" => array("to" => array("be" => array("nested"))))))
Run Code Online (Sandbox Code Playgroud)
den*_*ned 23
这是一个可能的实现:
<?php
function make_nested($array) {
if (count($array) < 2)
return $array;
$key = array_shift($array);
return array($key => make_nested($array));
}
print_r(make_nested(array("I", "need", "this", "to", "be", "nested")));
Run Code Online (Sandbox Code Playgroud)
如果你不喜欢递归,这里是一个迭代版本:
function make_nested($array) {
if (!$array)
return array();
$result = array(array_pop($array));
while ($array)
$result = array(array_pop($array) => $result);
return $result;
}
Run Code Online (Sandbox Code Playgroud)
Kob*_*obi 17
使用array_reduce:
$a = ["I", "need", "this", "to", "be", "nested"];
$result = array_reduce(array_reverse($a), function($prevArray, $key){
return $prevArray ? [$key => $prevArray] : [$key];
}, null);
Run Code Online (Sandbox Code Playgroud)
请注意,我们正在使用,array_reverse因为没有左减少.
工作示例:http://ideone.com/N61VtE
这是一个只改变原始数组而不是使用array_walk以下方法创建新变量的方法:
$a = ["I", "need", "this", "to", "be", "nested"];
array_walk(array_reverse($a), function ($v, $k) use (&$a) {
$a = $k ? [$v => $a] : [$v];
});
Run Code Online (Sandbox Code Playgroud)
如果$a为空,则应将其保留为空.但是,它确实假设您的输入数组具有从0开始的键.
| 归档时间: |
|
| 查看次数: |
1228 次 |
| 最近记录: |