Mark Henry
Mark Henry

Reputation: 2699

return results from a query in php

I have got this results of a query: (book_id, yr)

37 2014 
37 2012
35 2013
35 2012
35 2011

I would like to echo it like this

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

Upvotes: 3

Views: 54

Answers (2)

Kevin
Kevin

Reputation: 41885

One way would be to group them inside a container, then just use min and max:

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

Upvotes: 1

DocRattie
DocRattie

Reputation: 1423

$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);

with that you iterate over you books and collect the years. Every time you find a new ID you echo the old entry with all the years you collectet. In the end you echo the last entry aswell.

Upvotes: 0

Related Questions