Arc*_*ela 1 php arrays recursion
我在使用PHP创建递归数组时遇到问题.
我需要将此字符串格式化为多维数组,其中以点分隔的元素表示多个级别的数组键.
$str = "code.engine,max_int.4,user.pre.3,user.data.4";
Run Code Online (Sandbox Code Playgroud)
此示例的输出将是:
$str = array(
"code" => "engine",
"max_int" => 4,
"user" => array(
"pre" => 3,
"data" => 4
)
);
Run Code Online (Sandbox Code Playgroud)
我将从一个explode函数开始,但我不知道如何从那里对它进行排序,或者如何完成foreach.
您可以使用逗号开始拆分,,然后按点拆分每个项目.,删除最后一部分以获取"值",其余部分作为"路径".最后,遍历"path"来存储值:
$str = "code.engine,max_int.4,user.pre.3,user.data.4";
$array = [] ;
$items = explode(',',$str);
foreach ($items as $item) {
$parts = explode('.', $item);
$last = array_pop($parts);
// hold a reference of to follow the path
$ref = &$array ;
foreach ($parts as $part) {
// maintain the reference to current path
$ref = &$ref[$part];
}
// finally, store the value
$ref = $last;
}
print_r($array);
Run Code Online (Sandbox Code Playgroud)
输出:
Array
(
[code] => engine
[max_int] => 4
[user] => Array
(
[pre] => 3
[data] => 4
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |