【问题标题】:Index php array by array variable [duplicate]按数组变量索引php数组[重复]
【发布时间】:2017-05-22 01:23:29
【问题描述】:

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

【问题讨论】:

  • 您想使用.htaccess 还是使用 PHP 本身?
  • 变量 $url 只是一个例子。我需要它用于 PHP 中的类似用例。

标签: php arrays


【解决方案1】:

您可以像这样使用参考来获取它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2013-03-12
    • 2011-11-25
    • 2017-11-01
    • 2010-10-28
    相关资源
    最近更新 更多