SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Evangelist
    Join Date
    Jan 2005
    Posts
    425
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Ordering an array help

    Hi

    I'm crap with arrays.

    I've installed a WP plugin and the plugin uses an array. I want to order the array, by length (longest to shortest).

    For example (using sample data, printed, using print_r):
    PHP Code:
    Array
    (
        [
    balance transfer credit card] => /balance-transfer-credit-cards|0|1|0|1|0|0|0|balance transfer credit cards
        
    [balance transfer credit cards] => /balance-transfer-credit-cards|0|1|0|1|0|0|0|balance transfer credit cards
        
    [amet] => /|0|1|0|0|0|0|0|Amet
        
    [low rate credit cards] => /low-rate-credit-cards|0|1|0|0|0|0|0|
        [
    credit cards] => /credit-cards|0|1|0|0|0|0|0|

    Would become:
    PHP Code:
    Array
    (
        [
    balance transfer credit cards] => /balance-transfer-credit-cards|0|1|0|1|0|0|0|balance transfer credit cards
        
    [balance transfer credit card] => /balance-transfer-credit-cards|0|1|0|1|0|0|0|balance transfer credit cards
        
    [low rate credit cards] => /low-rate-credit-cards|0|1|0|0|0|0|0|
        [
    credit cards] => /credit-cards|0|1|0|0|0|0|0|   
        [
    amet] => /|0|1|0|0|0|0|0|Amet  
        

    So, sorting (longest to shortest) the left side of the arrow ( => )

    Thank you

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Try this:
    PHP Code:
    <?php
    $array 
    = array(
        
    'ccc'        => 3,
        
    'bb'        => 2,
        
    'dddd'    => 4,
        
    'a'            => 1
    );

    function 
    key_length_sort($a$b){
        
    $a strlen($a);
        
    $b strlen($b);
        if(
    $a === $b){
            return 
    0;
        }
        return 
    $a $b : -;
    }

    uksort($array'key_length_sort');

    print_r($array);

    /*
        Array
        (
                [dddd] => 4
                [ccc] => 3
                [bb] => 2
                [a] => 1
        )
    */
    Let me know if you get stuck.

    Anthony.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Evangelist
    Join Date
    Jan 2005
    Posts
    425
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yep, that works great, thanks!
    I tried usort earlier, which didn't work. but uksort worked a charm.

    Thanks.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •