【问题标题】:Reference an associative array from inside a string?从字符串内部引用关联数组?
【发布时间】:2011-04-06 02:06:41
【问题描述】:

"CREATE TABLE IF NOT EXISTS $tables[users]";

工作但..

"CREATE TABLE IF NOT EXISTS $tables['users']";

没有。

我不想这样做

$usersTable = $tables['users'];
"CREATE TABLE IF NOT EXISTS $usersTable";

我听说从关联数组中引用一个没有某种引号的键被认为是不好的做法。这是真的还是我首选的第一种方式?

【问题讨论】:

  • 如果它那么糟糕,它就不会工作。
  • 那么这不是不好的做法吗?我宁愿使用这种方法,因为它需要最少的标记,但我认为有理由不使用它。

标签: php arrays associative-array


【解决方案1】:

你可以用大括号做到这一点:

"CREATE TABLE IF NOT EXISTS {$tables['users']}";

或者通过串联:

'CREATE TABLE IF NOT EXISTS ' . $tables['users'];

【讨论】:

    【解决方案2】:

    你可以做以下事情:

    $query = sprintf("CREATE TABLE IF NOT EXISTS %s", $tables['users']);
    
    // do some other stuff
    

    【讨论】:

      【解决方案3】:

      你可以使用大括号。

      "CREATE TABLE IF NOT EXISTS {$tables['users']}"; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-10
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        相关资源
        最近更新 更多