【问题标题】:Am unable to remove messages that are nested within $_SESSION array using a foreach loop, unset无法使用 foreach 循环删除嵌套在 $_SESSION 数组中的消息,未设置
【发布时间】:2015-07-03 15:37:54
【问题描述】:

由于某种原因,我下面的代码不能完全正常工作。我一直无法取消设置数组元素。否则,代码似乎有效。我正在使用 echo javascript alert 来确认数组中存在的元素。也许问题与 $_SESSION 变量的性质有关?

数组是这样的,

Array
(
    [commerce_cart_orders] => Array
    (
        [0] => 33
    )

[messages] => Array
    (
        [error] => Array
            (
                [0] => Notice: Use of undefined constant actions - assumed 'actions' in mytheme_form_alter() …..
                [1] => Notice: Use of undefined constant submit - assumed 'submit' in mytheme_form_alter() ….
                [2] => Notice: Use of undefined constant actions - assumed 'actions' in mytheme_form_alter() ….
                [3] => Notice: Use of undefined constant submit - assumed 'submit' in mytheme_form_alter() ….

到目前为止我的代码是这样的,

$toRemoveOne = "Notice: Use of undefined constant actions - assumed 'actions' in ";
$toRemoveTwo = "Notice: Use of undefined constant submit - assumed 'submit' ";
foreach ($_SESSION['messages']['error'] as $val) {
    if((strpos($val, $toRemoveOne) == true) || (strpos($val, $toRemoveTwo) == true)){
    echo '<script>alert("it exists")</script>';
     //unset($_SESSION['messages']['error'][$val]);
    unset($val);
} 

然后我打印出 $_SESSION 变量,它们仍然存在。 我在这里做错了什么?谢谢!

【问题讨论】:

  • 在 val 之前添加 &amp; - foreach ($_SESSION['messages']['error'] as &amp;$val)
  • @splash58 如果可以的话,我会避免使用&amp;。它可以产生weird results
  • 对不起,我错了。 &amp; 可以修改项目,但不能取消设置

标签: php arrays session


【解决方案1】:

尝试使用:

foreach ($_SESSION['messages']['error'] as $key => $val) {
   if((strpos($val, $toRemoveOne) == true) || (strpos($val, $toRemoveTwo) == true)){
    echo '<script>alert("it exists")</script>';
      //unset($_SESSION['messages']['error'][$val]);
    unset($_SESSION[$key]);
} 

$val 是按值而不是按引用传递的

【讨论】:

    【解决方案2】:

    RTM:http://php.net/strpos

    它可以返回匹配字符串的整数位置,也可以返回布尔值 false。它永远不会返回true== true 将被简单地视为== 1,并且由于您匹配的字符串出现在位置0,因此您正在执行0 == 1,并且 if() 永远不会触发。

    你想要:

    if (strpos(...) !== false)
                    ^^^
    

    相反。

    同样,foreach() 中的$val 是数组中值的副本。您正在取消设置该临时副本,而不是数组中实际存在的值。你需要unset($yourarray[$key])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 2015-07-17
      • 2016-07-25
      • 2015-07-15
      • 2011-02-20
      相关资源
      最近更新 更多