0

我想把“for”函数的降序结果。 示例:我有这个 PHP 代码:

<?php
$field[1] = "Field 1"; // 1
$field[2] = "Field 2"; // 2
$field[3] = "Field 3"; // 3
$field[4] = "Field 4"; // 4
$field[5] = "Field 5"; // 5
$field[6] = "Field 6"; // 6
$field[7] = "Field 7"; // 7
$field[8] = "Field 8"; // 8
$field[9] = "Field 9"; // 9
$field[10] = "Field 10"; // 10

$i = "10";

for ($n=1 ; $n < $i ; $n++ ) {

echo $field[$n];

}
?>

将显示:

Field 1
Field 2
Field 3
Field 4
Field 5
Field 6
Field 7
Field 8
Field 9
Field 10

我该怎么做才能显示降序?像这样:

Field 10
Field 9
Field 8
Field 7
Field 6
Field 5
Field 4
Field 3
Field 2
Field 1

有什么解决办法吗?提前致谢!

4

4 回答 4

6
foreach(array_reverse(range(1, 10), TRUE) as $key => $value)
{
  echo 'Field ' . $value;
}

从0开始。

于 2012-12-09T22:53:51.513 回答
4

不要使用 for 循环遍历数组。PHP 有一个可爱的foreach结构,它做得更好,也更方便。

foreach (array_reverse($field) as $value) {
    echo "$value\n";
}
于 2012-12-09T22:38:44.727 回答
3
for ($n=$i; $n>=1; $n--) {
    echo $field[$n];
}
于 2012-12-09T22:38:25.927 回答
0

查找array_reversehttp://php.net/manual/en/function.array-reverse.php

我同意 GoogleGuy,您还应该将您的 for 语句更改为 foreach

<?php
$field[1] = "Field 1"; // 1
$field[2] = "Field 2"; // 2
$field[3] = "Field 3"; // 3
$field[4] = "Field 4"; // 4
$field[5] = "Field 5"; // 5
$field[6] = "Field 6"; // 6
$field[7] = "Field 7"; // 7
$field[8] = "Field 8"; // 8
$field[9] = "Field 9"; // 9
$field[10] = "Field 10"; // 10

$reversed = array_reverse($field); 

foreach ( $reversed AS $element )

 echo $element;

}
?>
于 2012-12-09T22:38:12.353 回答