Printing unique elements from MySQL Arrays??

  • RedBMedia
  • Proficient
  • Proficient
  • User avatar
  • Posts: 315

Post 3+ Months Ago

So, I have a MySQL table that holds ZIP codes, City, and State names. I want to list all the cities for each state, however, because many times there is more than one ZIP for each city I am having trouble listing each city only one time each. You can see my code below. I have tried using array_unique() for that isn't working right.

Have any ideas?

Code: [ Select ]
<ul class="a">
<?php
$citylookup = mysql_query("SELECT * FROM pages WHERE state_id ='$state_id' AND page_type ='2' ORDER BY title ASC");
while($cities = mysql_fetch_array($citylookup))
 { ?>
<li><a href="http://sitedomain.com/<?php echo $cities['slug']; ?>"><?php echo $cities['title']; ?></a></li>
<?php } ?>
</ul>    
  1. <ul class="a">
  2. <?php
  3. $citylookup = mysql_query("SELECT * FROM pages WHERE state_id ='$state_id' AND page_type ='2' ORDER BY title ASC");
  4. while($cities = mysql_fetch_array($citylookup))
  5.  { ?>
  6. <li><a href="http://sitedomain.com/<?php echo $cities['slug']; ?>"><?php echo $cities['title']; ?></a></li>
  7. <?php } ?>
  8. </ul>    
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9086
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

If you used a GROUP BY statement at the end you could group by each unique city, or you could also use a SELECT DISCTINCT clause at the beginning. So the MySQL statement might look like:

MYSQL Code: [ Select ]
SELECT slug, title
FROM pages
WHERE state_id ='$state_id'
AND page_type ='2'
GROUP BY title
ORDER BY title ASC
  1. SELECT slug, title
  2. FROM pages
  3. WHERE state_id ='$state_id'
  4. AND page_type ='2'
  5. GROUP BY title
  6. ORDER BY title ASC
  • RedBMedia
  • Proficient
  • Proficient
  • User avatar
  • Posts: 315

Post 3+ Months Ago

AWESOME! GROUP BY title works like a charm! Thanks!

Post Information

  • Total Posts in this topic: 3 posts
  • Users browsing this forum: No registered users and 70 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.