如何在PHP中将字符串转换为多维递归数组? [英] How to convert a string to a multidimensional recursive array in PHP?

查看:69
本文介绍了如何在PHP中将字符串转换为多维递归数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用PHP创建递归数组时遇到问题.

I have a problem with creating a recursive array with PHP.

我需要将此字符串格式化为多维数组,并使用点分隔的元素表示多个级别的数组键.

I need to format this string to a multidimensional array with the dot-separated elements indicating multiple levels of array keys.

$str = "code.engine,max_int.4,user.pre.3,user.data.4";

此示例的输出为:

$str = array(
   "code" => "engine",
   "max_int" => 4,
   "user" => array(
      "pre" => 3,
      "data" => 4
   )
);

我将从 explode 函数开始,但是我不知道如何从那里对它进行排序,或者如何完成foreach.

I will start with an explode function, but I don't know how to sort it from there, or how to finish the foreach.

推荐答案

您可以开始使用逗号进行拆分,,然后,用点拆分每个项目.最后一部分获得值",其余部分作为路径".最后,在路径"上循环以存储值:

You could start to split using comma ,, then, split each item by dot ., remove the last part to get the "value", and the rest as "path". Finally, loop over the "path" to store the value:

$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);

输出:

Array
(
    [code] => engine
    [max_int] => 4
    [user] => Array
        (
            [pre] => 3
            [data] => 4
        )

)

这篇关于如何在PHP中将字符串转换为多维递归数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆