我有一个小问题。我需要通过数组变量索引 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语言可以实现吗?
最佳答案
您可以使用引用来获取它,如下所示:
<?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)
关于php - 通过数组变量索引php数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41519961/