php unset not working

时间:2016-11-15 11:22:50

标签: php unset

好的,不知道为什么这不起作用

$ info包含一个数组,有3个user_pass副本应该被删除,前两个被删除,但第三​​个不是。

有什么想法吗?

if($phoneDetails['show_passwd'] == '0') {
    for($i = 0; $i < count($info); $i++) {
        if($info[$i]['header']['tag'] == 'user_pass') {
            unset($info[$i]);
        }elseif($info[$i]['header']['tag'] == 'http_pass') {
            unset($info[$i]);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您的代码依赖于数组索引从0N-1的事实。那真的是你的情况吗?如果您将for周期替换为foreach

,该怎么办?
if ($phoneDetails['show_passwd'] == '0') {
  foreach ($info as $i => $v) {  
    if ($info[$i]['header']['tag'] == 'user_pass']) {
      unset($info[$i]);
    } else if ($info[$i]['header']['tag'] == 'http_pass') {
      unset($info[$i]);
    }
  }
}

答案 1 :(得分:0)

您提供的代码相同,但重构更多。顺便说一下,我没有得到你真正需要的东西

if($phoneDetails['show_passwd'] == '0') { //or if(!$phoneDetails['show_passwd'])
    $i = 0;
    for($i; $i < count($info); $i++) { 
        $tag = !empty($info[$i]['header']['tag']) ? $info[$i]['header']['tag'] : '';
        if ($tag == 'user_pass' || $tag == 'http_pass') {
            unset($info[$i]);
        }
    }
}