Display alphabetical categorized list from array

Views: 38 Last modified: August 03rd, 2011 Comments: 0

You can fill an array with, for example, category names along with the associated url, and display them in an alphabetical order, categorized on alphabetical character. It will show the alphabetical character followed with their associated categories.

<?php
// Store the titles and urls
$categories = array( 'Food' => '/cats/food',
                     'Birds' => '/cats/birds',
                     'Movies' => '/cats/movies',
                     'Cars' => '/cats/cars',
                     'Bikes' => '/cats/biks',
                     'Work' => '/cats/work',
                     'Home' => '/cats/home',
                     'Useles' => '/cats/useles'
                     );

// Sort array ASC on keys
ksort( $categories );

// Defina range A - Z
$Alpha = range( 'a', 'z' );

// Flip array
$flipped = array_flip( $categories );

// New array ordered
$New_Ordered = array();

// Loop through Alphabet
foreach ( $Alpha as $key => $letter ):
    // Loop through sorted categories array
	foreach ( $flipped as $url => $cat ):
        // If first letter word matches letter from itteration
		if ( strtolower( $cat[0] ) == $letter ):
            // Put it into the array
			$New_Ordered[$letter][] = array( $url, $cat );
		endif; // end if
	endforeach; // end foreach
endforeach; // end foreach

// Loop through the array and display titles
foreach ( $New_Ordered as $character => $array ):
	// Echo Letter uppercased
	echo '<span style="font-size: 14px;">&raquo; ' . strtoupper( $character ) . '</span>';
	echo '<ul>';
    // Create list item including link
	foreach ( $array as $index => $arr ):
		echo '<li><a href="' . $arr[0] . '" target="_blank">' . $arr[1] . '</a></li>';
	endforeach;
	echo '</ul>';
endforeach; // end foreach
?>
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)
    Bluehost

    Mail this!

    To: From:Sum {7+9} =  
    Anything to add ?

        You must be logged in to post a comment.