【问题标题】:Remove specific value of array删除数组的特定值
【发布时间】:2014-10-12 03:31:00
【问题描述】:

我想删除数组的特定值。这是我的代码:

HTML

<form action="" method="post">
<input type="text" name="user">
<input type="submit" value="Watch">
</form>

PHP

$user='';

if ( isset ( $_POST['user'] ) ) { $user = $_POST['user']; }

$dir = "images/".$user.'/';

$dh = opendir ( $dir );

while ( false !== ($filename = readdir( $dh ) ) ) {
    $files[] = $filename; 
}

$files = array_diff ( $files, array('.','..') );

$e = count($files);

for ( $i=0; $i<$e; $i++ ) { echo $files[$i]; }

输出

user/.
user/..
user/HTML.txt
user/CSS.txt
user/JavaScript.txt

我尝试array_diff() 删除'.''..'

我注意到最新 WAMP 的偏移量为 0。

以及如何使 While 版本到 For 版本循环使用 opendirreaddir? p>

【问题讨论】:

  • 想要的输出是什么
  • Removing array item by value 的可能重复项
  • Utkarsh : 我想删除 ...。但我在For i 变量值 上收到通知偏移量 0
  • pc-shooter :感谢您的标签。但答案已经在我的代码中了。我注意到偏移量 0 的错误。

标签: php


【解决方案1】:

User If .. and condition 不需要使用array_diff

while ( false !== ($filename = readdir( $dh ) ) ) {
    if($filename != '.' && $filename != '..') {
        $files[] = $filename; 
    }
}

【讨论】:

    【解决方案2】:

    针对您的具体情况,建议使用 TBI 的答案;一开始就不要把它放在数组中是有意义的。但是,为了匹配您的问题的标题,从数组中删除一个元素,您应该使用unset

    foreach($files as $key => $file){
        if($file == '.' || $file =='..'){
            unset($key);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用if() 条件,例如 -

      while ( false !== ($filename = readdir( $dh ) ) ) {
          if($filename != '.' || $filename != '..') {
              $files[] = $filename; 
          }
      }
      

      现在,你不需要使用array_diff

      【讨论】:

      • TBI : 上面的代码中有错误的表达。 ||。它应该是 &&。谢谢你:)
      猜你喜欢
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 2020-07-24
      • 2020-08-11
      相关资源
      最近更新 更多