【问题标题】:How To Use An Array (Associative) As Header? [duplicate]如何使用数组(关联)作为标题? [复制]
【发布时间】:2020-04-24 14:10:14
【问题描述】:
if ($source=="test") {
header("Location: $testurl['google']"); 
}

如果 url 是 example.com/redirect.php?source=test,这应该重定向到 google.com,但它不起作用。如果我将数组键更改为 1 并将位置更改为 $testurl[1] 它确实有效。为什么它适用于索引数组而不是关联数组?

【问题讨论】:

  • 它的错字,用作if ($source=="test") { $url = $testurl['google']; header("Location:$url"); }

标签: php arrays url redirect header


【解决方案1】:

假设您在某处有一个数组$testurl,其中包含一个元素google

$testurl = [
  'google' => 'https://google.pl'
];

那么你可以这样使用它:

if ($source=="test") {
    header("Location: $testurl[google]"); 
}

if ($source=="test") {
    header("Location: {$testurl['google']}"); 
}

或者在我看来是最好的选择,像这样:

if ($source=="test") {
    header('Location: ' . $testurl['google']); 
}

它的定义很简单: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

有一句话:

// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";

【讨论】:

  • 谢谢,它有效!我使用了最好的选择。
猜你喜欢
  • 1970-01-01
  • 2011-10-02
  • 2018-11-29
  • 2020-12-09
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
相关资源
最近更新 更多