1

我有一个学年数组:

$arrayAcademicYears = array( 
           array("8889", "1988-1989"),
           array("8990", "1989-1990"),
           array("9091", "1990-1991"),
           array("0405", "2004-2005"),
           array("1112", "2011-2012"),
           array("1213", "2012-2013")
         );
         foreach($arrayAcademicYears as $k => $v) {
             echo "KEY: ";
             echo $v[0];
             echo " -> VALUE: ";
             echo $v[1];
             echo "<br>";
         }

这打印:

KEY: 8889 -> VALUE: 1988-1989
KEY: 8990 -> VALUE: 1989-1990
KEY: 9091 -> VALUE: 1990-1991
KEY: 0405 -> VALUE: 2004-2005
KEY: 1112 -> VALUE: 2011-2012
KEY: 1213 -> VALUE: 2012-2013

然后我有一个像这样的变量的当前学年:

$currentAcademicYear="1112";

如何更改要打印的代码:

KEY: 1112 -> VALUE: 2011-2012
KEY: 1213 -> VALUE: 2012-2013
KEY: 0405 -> VALUE: 2004-2005
KEY: 9091 -> VALUE: 1990-1991
KEY: 8990 -> VALUE: 1989-1990
KEY: 8889 -> VALUE: 1988-1989

请注意,这只是一个示例,我并不是要为任何类型的学术课程练习寻求解决方案。这里只是一个自学的 PHP 学习者。

非常感谢!(.. 帮助我成为一个更好的 PHP 程序员 :))

4

2 回答 2

0

这将反转您的数组,首先显示最新的:

$arrayAcademicYears = array_reverse($arrayAcademicYears);

把它放在上面:

foreach($arrayAcademicYears as $k => $v) {

Array_reverse 将出于某种原因将所有项目上的密钥更改为 0 增量,但 04-05 年除外。使用以下更新的函数,将实现正确的排序。

    function array_mtf(&$arr, $keytom, $reverse = false){
        $tmp = array();
        foreach($arr as $key => $value){
            if($key == $keytom){
                $tmp[$key] = $value;
                unset($arr[$key]);
            }
        }

                    if($reverse)
            arsort($arr);

        $arr = $tmp + $arr;
    }

用法如下:

array_mtf($array_to_sort, $key_to_move_first, true);    

因此,将功能块添加到您的代码中,然后替换:

$arrayAcademicYears = array_reverse($arrayAcademicYears);

array_mtf($arrayAcademicYears, $currentAcademicYear);   

结果数组如下所示:

Array
(
[1112] => 2011-2012
[1213] => 2012-2013
[0405] => 2004-2005
[9091] => 1990-1991
[8990] => 1989-1990
[8889] => 1988-1989
)
于 2012-06-25T15:49:38.110 回答
0

正如您想学习的那样,我建议您使用更简单的逻辑,仅使用一个数组,如下所示:

// Creating an array with associative keys
$arrayAcademicYears = array( 
    "8889" => "1988-1989",
    "8990" => "1989-1990",
    "9091" => "1990-1991",
    "0405" => "2004-2005",
    "1112" => "2011-2012",
    "1213" => "2012-2013"
    );

// Defining the current year
$currentAcademicYear = "1112";

// Printing the key and content of the current year
echo "KEY: " . $currentAcademicYear . " -> VALUE: " . $arrayAcademicYears[$currentAcademicYear] . "<br />";

// Removing from array the key printed above
unset($arrayAcademicYears[$currentAcademicYear]);

// Getting a reverse array, preserving the keys using the "true" parameter
$arrayAcademicYears = array_reverse($arrayAcademicYears, true);

// Now printing the other keys and its contents, following your logic
foreach($arrayAcademicYears as $key => $value)
    echo "KEY: " . $key . " -> VALUE: " . $value . "<br />";

希望它可以帮助你!

于 2012-06-25T16:12:05.910 回答