MrF*_*Fix 4 php arrays iteration nested
说,我们有一个数组:array(1,2,3,4,...)
我想将其转换为:
array(
1=>array(
2=>array(
3=>array(
4=>array()
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
谢谢
编辑通过迭代获得解决方案会很好.
Gre*_*nih 10
$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
$temp = array($array[$i] => $temp);
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地创建一个递归函数:
<?php
function nestArray($myArray)
{
if (empty($myArray))
{
return array();
}
$firstValue = array_shift($myArray);
return array($firstValue => nestArray($myArray));
}
?>
Run Code Online (Sandbox Code Playgroud)
好吧,尝试这样的事情:
$in = array(1,2,3,4); // Array with incoming params
$res = array(); // Array where we will write result
$t = &$res; // Link to first level
foreach ($in as $k) { // Walk through source array
if (empty($t[$k])) { // Check if current level has required key
$t[$k] = array(); // If does not, create empty array there
$t = &$t[$k]; // And link to it now. So each time it is link to deepest level.
}
}
unset($t); // Drop link to last (most deep) level
var_dump($res);
die();
Run Code Online (Sandbox Code Playgroud)
输出:
array(1) {
[1]=> array(1) {
[2]=> array(1) {
[3]=> array(1) {
[4]=> array(0) {
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10148 次 |
| 最近记录: |