2015-11-07 40 views
1

调用函数未正确检查数组中是否存在该值?

$user->setError("h", "h", "error"); 
$user->setError("h2", "h", "error");` 

功能:

public function setError($title, $msg, $type) { 
     if(!isset($_SESSION['messages'])) { 
      $_SESSION['messages'][] = array("title" => $title, "message" => $msg, "type" => $type); 
     } else { 
      $key = array_search($title, $_SESSION['messages']); 
      if($_SESSION['messages'][$key]['title'] !== $title) 
       $_SESSION['messages'][] = array("title" => $title, "message" => $msg, "type" => $type); 
     } 
    } 

出于某种原因,一直到阵列添加,我不知道我做错了。

在此先感谢

+0

变化'array_search($标题,$ _SESSION [ '消息']);'到'array_search($标题,array_column($ _ SESSION [ '消息'] ,'title'));' –

回答

0

每次函数调用将新的值存储到$ _SESSION [“消息”] []一个一后,如果您不想增加值,那么你已经清除(空)数组插入新值之前。公共函数setError($ title,$ msg,$ type){ $ _SESSION ['messages'] = array(); 。 。 }

0

array_search与单维数组一起工作,为了使它与多维数组一起工作,您需要在array_search函数中使用array_columnarray_colum将有两个你想要搜索的参数数组和列名。 在你的情况下,代码将是如下:

public function setError($title, $msg, $type) { 
    if(!isset($_SESSION['messages'])) { 
     $_SESSION['messages'][] = array("title" => $title, "message" => $msg, "type" => $type); 
    } else { 
     $key = array_search($title, array_column($_SESSION['messages'], 'title')); 
     if($_SESSION['messages'][$key]['title'] !== $title) 
      $_SESSION['messages'][] = array("title" => $title, "message" => $msg, "type" => $type); 
     } 
}