在循环中使用头函数

时间:2016-08-24 08:43:26

标签: php

<?php
$a = array('f-stat,porcelain mask'=>'jay azima','jay azima,oil painting'=>'japanese doll');
$msg="We can't recommend any items to you.";
foreach($a as $k=>$v)
{
  if($_GET['items']==$k)
  {
    header("location: hola.php?tequilla=".$v);
  }

}
header("location: hola.php?tequilla=".$msg);
?>

我尝试做的是,如果来自$_GET['items']的字符串与$a数组中的任何键匹配,则会将其重定向到值为$v的hola.php。否则传递$msg string。但问题是即使$k$_GET['items']匹配,后一个头函数也会以$msg值执行。此外,如果我删除后一个头函数,循环内的头函数工作正常。

3 个答案:

答案 0 :(得分:1)

简化了所有代码:

$a = array(
    'f-stat,porcelain mask'=>'jay azima',
    'jay azima,oil painting'=>'japanese doll'
);
$v = !empty($a[$_GET['items']])? $a[$_GET['items']] : "We can't recommend any items to you.";

header("Location: hola.php?tequilla=" . $v);
die();

答案 1 :(得分:0)

使用<?php $a = array('f-stat,porcelain mask'=>'jay azima','jay azima,oil painting'=>'japanese doll'); $msg="We can't recommend any items to you."; foreach($a as $k=>$v) { if($_GET['items']==$k) { header("location: hola.php?tequilla=".$v); exit(); // < this will stop the script before the 2nd header() } } header("location: hola.php?tequilla=".$msg); exit(); ?> 它会停止执行脚本。这不会重定向到第二个标头。

@group

答案 2 :(得分:0)

  

试试这个

<?php
  $a = array('f-stat,porcelain mask'=>'jay azima','jay azima,oil painting'=>'japanese doll');
  $location = '';
  $msg="We can't recommend any items to you.";
  foreach($a as $k=>$v){
    if($_GET['items']==$k){
       $location = "hola.php?tequilla=".$v;
    }
  }
  if($location != ''){
     $location = "hola.php?tequilla=".$msg;
  }
  header("location: ".$location);
  exit(0);
?>