Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Sort object array alphabetically and arrange according to first letter

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.90k
    Comment on it

    Sort the values of an Object array alphabetically in php and arrange them into sections of alphabets according to the first letter of their name.


    /* Code to sort the data elements in alphabetic order .

    The following snippet will sort the array alphabetically in ascending order, starting from 'a' to 'z' .  */

    <?php
    
    function compareByName($a, $b) {
      return strcmp($a->name, $b->name);
    }
    usort($cityPages->data, 'compareByName');   // $cityPages->data are the array which we want to sort.
    
    ?>

     

    /* Code to arrange the sorted data elements into their respective sections with the first letter of their names.

    */

    <?php 
    
    $previousalphabet = null;  // initialize the alphabets for to compare with next alphabets for the start.
    
    $initial_counter  = 1;
    
    foreach($cityPages->data as $value) {
    
      $firstalphabet = substr($value->name, 0, 1);      // extract the first alphabet of the word.
    
      if($previousalphabet !== $firstalphabet) {        // compare the first alphabet with  the previous alphabet.
    
        if($initial_counter!=1){ echo '</ul></li>'; } ?>  // if its not the first case then print the result in list tag.
    
        <li class="<?php echo strtolower($firstalphabet); ?> item masonry-brick">
    
        <h3><?php echo $firstalphabet; ?></h3>         // print the first alphabet whose section is going to start like A,B,C,D etc.
    
        <?php echo '<ul>';          //start the <ul> to print the results under above alphabet section.
      }
    
      $previousalphabet = $firstalphabet;       // replace the previous alphabet with the current one.
     
      echo '<li>'echo $value->name;        // print the value inside <li> under the individual alphabet.
    
      $initial_counter++;    // increase the counter 
    }
    
    ?>

     

    The output of the above code will be like : 

    Output format : 

    A                  B                 C                   D
    atlanta        Bosten        China            Denmark
    anapolis      Berlin          Charlotte      Detroit
    arkon

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: