【问题标题】:PHP variable variable array key listPHP变量变量数组键列表
【发布时间】:2011-01-30 12:41:37
【问题描述】:

我有一个可以使用的多维数组:

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

我怎样才能使这项工作......我有一个像这样的字符串的键列表:

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

我想使用键的字符串列表访问数组,怎么做? 这可行,但密钥显然是硬编码的:

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

谢谢, 克里斯

【问题讨论】:

  • 恭喜。你刚刚为我在 SO 上看到的根本性破坏的想法/代码设置了我的新个人记录。 “变量很简洁,但让我们看看我们能把它们带到多远......”

标签: php variables multidimensional-array key


【解决方案1】:
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'

如果你传入array(1, 2),而不是[1][2],那就更好了:可以避免(脆弱的)preg_match_all 解析。

【讨论】:

  • 我喜欢这种方法,因为它既优雅又安全。
  • 好吧,我不会称它为“优雅”,但至少它是安全的;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
  • 2014-03-16
  • 2020-07-05
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多