Jump to content

please could you help me with a loop


ricky spires

Recommended Posts

Hello .

 

im having trouble with a loop.

i want the title to only appear ones and have the items listed under each title but it seems to be echoing the title more than once.

 

 

i want to output something like this:

 

Category1

item1

 

Category2

item1

item2

 

etc...

 

but im getting this:

 

Category1

item1

 

Category2

item1

item2

 

Category2

item1

item2

 

 

 

in my database i have this:

 

id - book_id - cat - item

1 - 1 - cat1 - item1

2 - 1 - cat2 - item1

3 - 1 - cat2 - item2

 

 

 

my loop looks like this:

 

 

//this part finds the categories by book id.

$book_id = "1";
$bookCats = Categories::find_by_book($book_id);


//this part finds the books categories

foreach($bookCats as $bookCat){
$cat_name = $bookCat->category;

echo $cat_name;

//then in put the rest of the code here.....

}

 

this is how part of the class looks

 

 public static function find_by_book($book_id) {
 return self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE book_id={$book_id}");
}

 

 

 

the above code gives me:

 

cat1

cat2

cat2

 

 

i want it to only give me

 

cat1

cat2

 

 

 

 

thanks

ricky

Link to comment
Share on other sites

Yipppeeeee. It worked:)

 

:happy-04:

 

  public static function find_by_book($book_id) {
 return self::find_by_sql("SELECT DISTINCT cat FROM ".self::$table_name." WHERE book_id={$book_id} group by cat");
}

 

FYI, SELECT DISTINCT, is much higher overhead and should be avoided if possible, especially on large (hundres of thousands of records) databases; Make sure to run "EXPLAIN" on your sql to check for any performance hits, like using temporary and using filesort.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.