通过数组变量索引php数组

时间:2017-01-07 09:33:55

标签: php arrays

我有点问题。我需要通过数组变量索引一个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语言可以吗?

1 个答案:

答案 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)