php - separate a foreach loop's results by letter -


this query:

try {   $sql = 'select park_id, name, town, state, country           tpf_parks  order name asc';   $result = $pdo->query($sql); } catch (pdoexception $e) {   $error = 'error fetching parks: ' . $e->getmessage();   //include 'error.html.php';//   exit(); }  $output = 'parks loaded'; //include 'output.html.php';//  foreach ($result $row) {   $parklist[] = array(     'park_id' => $row['park_id'],     'name' => $row['name'],     'town' => $row['town'],     'state' => $row['state'],     'country' => $row['country']   ); } include 'parks.html.php'; 

and parks.html.php

<?php foreach ($parklist $park):?>     <a href="park.php?park_id=<?php echo $park['park_id'];?>">         <h2><?php echo $park['name'];?></h2>         <h3><?php echo $park['town'],',',$park['state'],',',$park['country'];?></h3>     </a>     <hr> <?php endforeach; ?> 

i'm looking way foreach loop can altered can split results groups sorted first letter. can put html anchor each letter making easier user locate particular record clicking link @ top of page (a b c d e etc) . clueless how achieve this.

well, it's not gonna prettiest solution unless use variable variables, allow create arrays , assign them based on loop array of letters of alphabet.

but if that's complex you, this:

$a = array(); $b = array(); $c = array(); ...  foreach ($result $row) {     $letter = strtolower(substr($row['name'], 0, 1));     if ($letter == 'a') $a.push($row);     else if($letter == 'b') $b.push($row);     ... } 

obviously, repeating every letter.

then, when loop through arrays html creation, you'll have foreach() through each letter array.


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

php - HTTP_REFERER woes: How can I allow access to a specific page, only when a visitor has visited another specific page beforehand? -

java Extracting Zip file -