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

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

WBOY
Release: 2016-06-06 20:21:40
Original
1633 people have browsed it

例子:
一维数组:

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

需要转变成的变量:

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

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

回复内容:

例子:
一维数组:

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

需要转变成的变量:

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

一维数组层级不定,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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template