当前位置: 动力学知识库 > 问答 > 编程问答 >

php - 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;
分享给朋友:
您可能感兴趣的文章:
随机阅读: