Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

php - String with array structure to Array


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given the values

$key = "Main.Sub.SubOfSub";
$target = array();
$value = "SuperData";

Here's some code I have lying around that does what you need1:

$path = explode('.', $key);
$root = &$target;

while(count($path) > 1) {
    $branch = array_shift($path);
    if (!isset($root[$branch])) {
        $root[$branch] = array();
    }

    $root = &$root[$branch];
}

$root[$path[0]] = $value;

See it in action.

1 Actually it does slightly more than that: it can be trivially encapsulated inside a function, and it is configurable on all three input values (you can pass in an array with existing values, and it will expand it as necessary).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...