从php中的查询返回结果

时间:2015-04-16 11:36:41

标签: php mysql

我有一个查询结果: (book_id,yr)

37 2014 
37 2012
35 2013
35 2012
35 2011

我想像这样回应它

book id is 37 from 2014
editions available are 2014 and 2012 

2 个答案:

答案 0 :(得分:1)

一种方法是将它们分组到容器中,然后只使用minmax

// grouping
$container = array();
while($row = your_fetch_assoc($result_set)) {
    $container[$row['book_id']][] = $row['yr'];
}

// then comes the presentation
foreach($container as $book_id => $year) {
    $to = max($year);
    $from = min($year);
    echo "
        book id is {$book_id} <br/>
        editions available are {$to} and {$from} <br/><br/>
    ";
}

答案 1 :(得分:0)

$years = array();
$id = 0;
foreach($row as $r){
  if( $r['book_id'] != $id && $id != 0){
    echo "book id is ".$id." editions available are ".implode('and ', $years);
    $years = array(); 
    $id = 0;
  }
  $id = $r['book_id'];
  $years[] =  $r['yr'];
}
echo "book id is ".$id." editions available are ".implode('and ', $years);

随着你迭代你的书籍和收集岁月。每当您找到新的ID时,您都会收集旧条目以及您收集的所有年份。最后你回应最后一个条目。