使用变量变量获取数组索引的值

时间:2011-09-27 13:52:12

标签: php arrays recursion

我的递归数组深度是可变的,我希望能够使用分隔符获取字符串并将该字符串转换为该数组中的索引,

例如

$path = 'level1.level2.level3';

将被转换为从下面的数组中获取值'my data'

$data['level1']['level2']['level3'] = 'my data';

我认为最快的方法是使用变量变量,但是当我尝试以下代码时

$index = "data['level1']['level2']['level3']";

echo $$index;

我收到了以下错误

PHP Notice:  Undefined variable: data['level1']['level2']['level3']

我能想到的所有其他方式都是非常低效的,有人可以对此有所了解,是否有可能在PHP中使用变量变量?还有其他有效的解决方法吗?

非常感谢。

5 个答案:

答案 0 :(得分:2)

你必须循环数组,据我所知,你不会设法使用变量变量。这似乎有效:

<?php

function retrieve( $array, $path ) {
    $current = $array;
    foreach( explode( '.', $path ) as $segment ) {
        if( false === array_key_exists( $segment, $current ) ) {
            return false;
        }
        $current = $current[$segment];
    }
    return $current;
}

$path = 'level1.level2.level3';

// will be converted to get the value 'my data' from the array below
$data['level1']['level2']['level3'] = 'my data';

var_dump( retrieve( $data, $path ) );

答案 1 :(得分:2)

这是一个棘手的问题,这是我能想到的最有效的方式:

function get_value_from_array ($array, $path, $pathSep = '.') {
  foreach (explode($pathSep, $path) as $pathPart) { 
    if (isset($array[$pathPart])) {
      $array = $array[$pathPart];
    } else { 
      return FALSE;
    }
  }
  return $array;
}

返回值,失败时返回FALSE。

答案 2 :(得分:0)

尝试

$index = "data";
echo $$index['level1']['level2']['level3'];

相反,因为$index应该只是变量名

答案 3 :(得分:-1)

这样的事情:

eval('$data[\''.implode("']['",explode('.',$path))."'] = 'my data';");

...但是,永远不要告诉任何我告诉过你的人。

答案 4 :(得分:-1)

您可以使用eval功能:

$data['level1']['level2']['level3'] = 'my data';
eval("\$index = \$data['level1']['level2']['level3'];");
echo $index;