php - 通过数组变量索引php数组

标签 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语言可以实现吗?

最佳答案

您可以使用引用来获取它,如下所示:

<?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/

相关文章:

php - 如何检查和设置 max_allowed_pa​​cket mysql 变量

java - 创建行和列

javascript - AngularJS : check if key/value exist in object and construct an array of objects

c - 为什么数组的值后面跟着三个零?

c# - LINQ 到 XML : result based on attributes

java - Java 中确定列表/数组是否实际上是重复的较小数组的好方法

php - 如何获取Linux系统的具体路径

php - MySQL 结果 ORDER BY 日期和时间

php - 使用 phpmsnclass 自动接受联系人

php - css样式和对齐问题