Home >Backend Development >PHP Tutorial >php如何将一维数组赋值到一个变量根据这个一维数组层层嵌套?

php如何将一维数组赋值到一个变量根据这个一维数组层层嵌套?

WBOY
WBOYOriginal
2016-06-06 20:21:401629browse

例子:
一维数组:

<code>$arr = ['a', 'b', 'c', 'd'];
</code>

需要转变成的变量:

<code>$tmp['a']['b']['c']['d'] = $value;</code>

一维数组层级不定,key不定。

回复内容:

例子:
一维数组:

<code>$arr = ['a', 'b', 'c', 'd'];
</code>

需要转变成的变量:

<code>$tmp['a']['b']['c']['d'] = $value;</code>

一维数组层级不定,key不定。

<code class="php">$arr = ['a', 'b', 'c', 'd'];

$x = [];
$y = &$x;
$value = 1234;

while ($key = current($arr)) {
    $y[$key] = [];
    $y = &$y[$key];
    next($arr);
}
$y = $value;

print_r($x);</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn