开发者

Getting a value of an array index using variable variable

I have a recursive array depth of which is variable, and I want to be able to take a string with a separator and convert that string to an index in that array,

For example

$path = 'level1.level2.level3';

will be converted to get the value 'my data' from the array below

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

I thought the quickest way to get this would be to use variable variables, but when I try the following code

$index = "data['level1'][开发者_开发问答'level2']['level3']";

echo $$index;

I get the follwing error

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

All other ways I can think of doing this are very inefficient, could someone please shed some light on this, is it possible using variable variables for arrays in PHP? Any other efficient workaround?

Many thanks.


You'll have to loop the array, you won't manage to do this using variable variables, as far as I know. This seems to work though:

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


It is a tricky one this, here is the most efficient way I can think of:

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;
}

Returns the value, or FALSE on failure.


Try

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

instead, because $index should be only variable name


Something like this:

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

...but don't ever, ever tell anyone I told you to do this.


You can use eval function like so:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜