Как я могу получить полный набор результатов запроса здесь?

0

Я написал следующую функцию модели CodeIgniter для захвата и повторения результатов запроса MySQL.

function get_book_info() {

/*
 * SELECT b.isbn, b.title, b.publisher, b.date, b.thumb, b.filename, b.pages, t.tag
 * FROM books AS b
 * INNER JOIN books_tags AS bt ON b.isbn = bt.book_id
 * INNER JOIN tags AS t ON bt.tag_id = t.id
 * ORDER BY b.title, t.tag
 */

$this->db->select('b.isbn, b.title, b.publisher, b.date, b.thumb, b.filename, b.pages, t.tag');
$this->db->from('books AS b');
$this->db->join('books_tags AS bt', 'b.isbn = bt.book_id', 'inner');
$this->db->join('tags AS t', 'bt.tag_id = t.id', 'inner');
$this->db->order_by('b.title, t.tag');
$query = $this->db->get();
$result = $query->result();

$counter = '';
$record = $meta = $tags = array();
foreach ($result as $book) {
    // If this is the first appearance of this book
    if ($counter != $book->isbn) {
        // If the meta array already exists
        if ($meta) {
            // Add the combined tag string to the meta array
            $meta['tags'] = implode(', ', $tags);
            // Add the meta array
            $record[] = $meta;
            // Empty the tags array
            $tags = array();
        }
        // Reset the counter
        $counter = $book->isbn;
        // Grab the book from Amazon
        $amazon = $this->amazon->get_amazon_item($book->isbn);
        // Collect the book information
        $meta = array(
            'isbn' => $book->isbn,
            'title' => strip_slashes($book->title),
            'publisher' => strip_slashes($book->publisher),
            'date' => date('F j, Y', strtotime($book->date)),
            'thumb' => $book->thumb,
            'filename' => $book->filename,
            'pages' => $book->pages,
            'rating' => $amazon->Items->Item->CustomerReviews->AverageRating,
            'raters' => $amazon->Items->Item->CustomerReviews->TotalReviews
        );
        // Add the tag to the tags array
        $tags[] = $book->tag;
    } else {
        // All we need is the tag
        $tags[] = $book->tag;
    }
}

return $record;
}

Код работает для всех, кроме последней книги - он всегда пропускает последнюю строку. Я понимаю, почему он это делает, но я не знаю, как это исправить. Здесь я попытался, но я до сих пор не получил последнюю книгу, включенную в массив $record.

function get_book_info() {

    /*
     * SELECT b.isbn, b.title, b.publisher, b.date, b.thumb, b.filename, b.pages, t.tag
     * FROM books AS b
     * INNER JOIN books_tags AS bt ON b.isbn = bt.book_id
     * INNER JOIN tags AS t ON bt.tag_id = t.id
     * ORDER BY b.title, t.tag
     */

    $this->db->select('b.isbn, b.title, b.publisher, b.date, b.thumb, b.filename, b.pages, t.tag');
    $this->db->from('books AS b');
    $this->db->join('books_tags AS bt', 'b.isbn = bt.book_id', 'inner');
    $this->db->join('tags AS t', 'bt.tag_id = t.id', 'inner');
    $this->db->order_by('b.title, t.tag');
    $query = $this->db->get();
    $result = $query->result();

    $counter = '';
    $record = $meta = $tags = array();
    $count = count($result);
    $i = 0;

    foreach ($result as $book) {
        // If this is not the last row
        if ($i < $count) {
            // If this is the first appearance of this book
            if ($counter != $book->isbn) {
                // If the meta array already exists
                if ($meta) {
                    // Add the combined tag string to the meta array
                    $meta['tags'] = implode(', ', $tags);
                    // Add the meta array
                    $record[] = $meta;
                    // Empty the tags array
                    $tags = array();
                }
                // Reset the counter
                $counter = $book->isbn;
                // Grab the book from Amazon
                $amazon = $this->amazon->get_amazon_item($book->isbn);
                // Collect the book information
                $meta = array(
                    'isbn' => $book->isbn,
                    'title' => strip_slashes($book->title),
                    'publisher' => strip_slashes($book->publisher),
                    'date' => date('F j, Y', strtotime($book->date)),
                    'thumb' => $book->thumb,
                    'file' => $book->filename,
                    'pages' => $book->pages,
                    'rating' => $amazon->Items->Item->CustomerReviews->AverageRating,
                    'raters' => $amazon->Items->Item->CustomerReviews->TotalReviews
                );
                // Add the tag to the tags array
                $tags[] = $book->tag;
            } else {
                // All we need is the tag
                $tags[] = $book->tag;
            }
        // If this is the last row
        } else {
            // If this is the first appearance of this book
            if ($counter != $book->isbn) {
                // Grab the book from Amazon
                $amazon = $this->amazon->get_amazon_item($book->isbn);
                // Collect the book information
                $meta = array(
                    'isbn' => $book->isbn,
                    'title' => strip_slashes($book->title),
                    'publisher' => strip_slashes($book->publisher),
                    'date' => date('F j, Y', strtotime($book->date)),
                    'thumb' => $book->thumb,
                    'file' => $book->filename,
                    'pages' => $book->pages,
                    'rating' => $amazon->Items->Item->CustomerReviews->AverageRating,
                    'raters' => $amazon->Items->Item->CustomerReviews->TotalReviews
                );
                // Add the tag to the tags array
                $tags[] = $book->tag;
                // Add the combined tag string to the meta array
                $meta['tags'] = implode(', ', $tags);
                // Add the meta array
                $record[] = $meta;
            } else {
                // All we need is the tag
                $tags[] = $book->tag;
                // Add the combined tag string to the meta array
                $meta['tags'] = implode(', ', $tags);
                // Add the meta array
                $record[] = $meta;
            }
        }
        $i++;
    }

    return $record;
}

Любые предложения? Как я могу это исправить?

  • 0
    Просто чтобы спросить ... Я верю, что вам не хватает последней книги, но как вы узнали об этом? Вы делаете var_dump () на $ record, чтобы увидеть, что было заполнено?
  • 0
    print_r ($ запись);
Теги:
codeigniter

1 ответ

0
Лучший ответ

Я понял это. У меня это было почти правильно во втором примере, мне просто нужно было инициализировать мой счетчик $i 1 вместо 0

$i = 1;
  • 1
    Это заняло всего 9 минут!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню