在foreach / switch中添加一条不可重复的行

时间:2015-07-23 13:05:23

标签: php arrays object foreach switch-statement

我有这个循环,它显示一年内的书籍:

foreach ($cases_result as $case) {
    $i = $case->n_ano;
    switch ($i) {

        case $i >= 2013:
            echo $case->book.'<br>';
            break;

        case $i <= 2012 && $i >= 2011:
            echo $case->book.'<br>';
            break;
        case $i <= 2010 && $i >= 2009:
            echo $case->book.'<br>';
            break;
        case $i <= 2008 && $i >= 2007:
            echo $case->book.'<br>';
            break;
    }

}

是否可以添加不可重复的行来分隔每个案例?

我需要展示这一年,就像这样:

2013
 - book 1
 - book 2
2012
 - book 3
 - book 4

以下是该数组的摘录:

array (size=22)
  0 => 
    object(stdClass)[14]
      public 'book' => string 'book 1' (length=6)
      public 'n_ano' => string '2013' (length=4)
  1 => 
    object(stdClass)[15]
      public 'book' => string 'book 2' (length=6)
      public 'n_ano' => string '2013' (length=4)
  2 => 
    object(stdClass)[16]
      public 'book' => string 'book 3' (length=6)
      public 'n_ano' => string '2012' (length=4)

2 个答案:

答案 0 :(得分:1)

这应该适合你:

首先我创建一个数组,它使用year作为键并将书名添加到数组中,这样你就可以简单地循环它,例如。

<?php

    foreach($arr as $v)
            $data[$v->n_ano][] = $v->book;

    foreach($data as $n_ano => $books) {
        echo $n_ano . "<br>";
        foreach($books as $book)
            echo " - " . $book . "<br>";
    }

?>

输出:

2013
 - book 1
 - book 2
2012
 - book 3

答案 1 :(得分:0)

首先,按n_ano对数组进行排序。然后,您可以轻松循环调整排序结果并创建分组输出。

function sortCases($a, $b) {
    return $a->n_ano < $b->n_ano;
}

usort($cases_result, "sortCases");

$out = '';
$i = 0;
foreach ($cases_result as $case) {

    //If the year is different, print year and assign it so $i
    if($i !== intval($case->n_ano)) {
        $out .= '<h2>' . $case->n_ano . '</h2>';
        $i = intval($case->n_ano);
    }

    $out .= $case->book . '<br>';
}

print $out;