dongren1353 2011-01-30 12:41
浏览 44

PHP变量变量数组键列表

I have a multidimensional array where this works:

print_r( $temp[1][0] );

How can I make this work... I have the list of keys as a string like this:

$keys = "[1][0]";

I want to access the array using the string list of keys, how can it be done? This works but the keys are obviously hard coded:

$keys = "[1][0]";
$tempName = 'temp';

print_r( ${$tempName}[1][0] );

// tried lots of variations like, but they all produce errors or don't access the array
print_r( ${$tempName.${$keys}} );

Thanks, Chris

  • 写回答

1条回答 默认 最新

  • douzhi7451 2011-01-30 12:47
    关注
    function accessArray(array $array, $keys) {
        if (!preg_match_all('~\[([^\]]+)\]~', $keys, $matches, PREG_PATTERN_ORDER)) {
            throw new InvalidArgumentException;
        }
    
        $keys = $matches[1];
        $current = $array;
        foreach ($keys as $key) {
            $current = $current[$key];
        }
    
        return $current;
    }
    
    echo accessArray(
        array(
            1 => array(
                2 => 'foo'
            )
        ),
        '[1][2]'
    ); // echos 'foo'
    

    Would be even nicer, if you passed in array(1, 2), instead of [1][2]: One could avoid the (fragile) preg_match_all parsing.

    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏