在for循环中按数字输出

时间:2017-07-06 21:46:26

标签: php arrays loops

这是什么语法?我想输出不是每个结果,但我想按数字输出。例如,1到20个结果等。或者只有第1,第3和第5个结果。我可以制作一系列结果吗?

for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

// I want to output something like the following in the for loop:
  echo $target_path[0],
  echo $target_path[5],
  echo $target_path[3],
}

3 个答案:

答案 0 :(得分:3)

前20:

for($i = 0; $i < count($_FILES['file']['name']) && $i < 20; $i++) {
    // ...
}

对于第一,第三,第五等元素:

for($i = 0; $i < count($_FILES['file']['name']); $i += 2) {
    // ...
}

或者通常对于任何条件:

for($i = 0; $i < count($_FILES['file']['name']); $i++) {
    if(/* condition */) {
        // ...
    }
}

或者此表单可以防止不必要的缩进:

for($i = 0; $i < count($_FILES['file']['name']); $i++) {
    if(/* !condition */) {
        continue;
    }
    // ...
}

答案 1 :(得分:1)

使用Modulo算术运算符,您可以根据索引进行回显。

来自http://php.net/manual/en/language.operators.arithmetic.php

if(($i % 2) == 1)  //odd
}

所以这应该有效:

for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];
  if(($i % 2) == 1)
      echo $target_path;
  }
}

答案 2 :(得分:0)

你可以使用foreach来代替你输入条件以获得你想要的索引。

//If you need an array of results
$results = [];
foreach ($_FILES['file']['name'] as $index => $file) {
  $ext = explode('.', basename($file))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

    //here you can put your conditions
    //example:
    //if you need only index < 20  
    if($index < 20){

     //if yo need only odd index: (0,2,4,6 ...)
      if ($index % 2 == 1) {

        //if you need to save only file 
        $results[] = $file;

        //if you need to save only index
        $results[] = $index;

        //if you need both (index and file)
        $results[] = [$index,$file];

        //same for your variable $target_path
        //Don't forget: If you use one of above examples you need to comment the others what you don't need.

      }else{
        //here you can do idem as above but for even index (1,3,5 ... etc)
      }
    }

}