我有点问题。我需要通过数组变量索引一个php数组。
示例:
$structure = [];
$url = "/one/two/three";
$urlParts = explode("/", $url);
// I need convert $urlParts -> to array index ["one"]["two"]["three"]
// Expected result
$structure["one"]["two"]["three"] = true;
用php语言可以吗?
答案 0 :(得分:3)
您可以使用引用来实现:
<?php
$urlParts = ['one', 'two', 'three'];
$o = [];
$ref = &$o;
$len = count($urlParts);
foreach($urlParts as $k => $v)
{
$ref[$v] = [];
$ref = &$ref[$v];
}
$ref = true;
var_dump($o);
echo var_dump($o['one']['two']['three']);
输出:
ei@localhost:~$ php test.php
array(1) {
["one"]=>
array(1) {
["two"]=>
array(1) {
["three"]=>
&bool(true)
}
}
}
bool(true)