String to multidimensional/recursive array in PHP

女生的网名这么多〃 提交于 2021-02-19 08:25:06

问题


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";

The output for this example would be:

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

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


回答1:


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

Outputs:

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

)


来源:https://stackoverflow.com/questions/49563864/string-to-multidimensional-recursive-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!