2015-04-16 65 views
3

我有一個查詢的這個結果返回結果: (book_id,年)從查詢在PHP

37 2014 
37 2012 
35 2013 
35 2012 
35 2011 

我想呼應像這樣

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

'distinct'或'組by'可能在這種情況下是很方便,不是嗎? –

+0

使用'foreach'循環函數並創建一個'索引數組',其中'key'是你的'book id','value'是你的'edition'並且檢查'array'中'book id'是否已經更新''值'用逗號分開。 – ajaykumartak

+0

這可能是有用的'GROUP_CONCAT(版本ORDER BY版本ASC)'和'GROUP BY book_id' –

回答

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/> 
    "; 
} 
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); 

隨着你迭代你的書籍和收集年。每當你找到一個新的身份證號碼,你都會回憶你收集的所有年份的舊記錄。最後,你也迴應最後一個條目。