Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

Can't get usort working

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Can't get usort working

Postby andyk » Sun May 12, 2013 5:29 am

This code does not sort $fruits, can anyone please see why not?

Code: Select all
function buildForm(&$form) {
   //lots of code in here

   $fruits = array();
                       
   $fruits[0]["weight"] = "3";
   $fruits[0]["fruit"] = "apple";
   $fruits[1]["weight"] = "1";
   $fruits[1]["fruit"] = "orange";
   $fruits[2]["weight"] = "2";
   $fruits[2]["fruit"] = "pineapple";

   usort ($fruits,"sort_by_weight");
   //lots more code in here
}

function sort_by_weight($a, $b) {
    if ($a['weight'] == $b['weight']) {
        return 0;
    }
    return ($a['weight'] < $b['weight']) ? -1 : 1; 
  }
andyk
New php-forum User
New php-forum User
 
Posts: 2
Joined: Sun May 12, 2013 5:20 am

Re: Can't get usort working

Postby andyk » Sun May 12, 2013 5:42 am

Sorry forget I asked, the sort_by_weight function is inside a class so usort needs to look like this:

Code: Select all
usort ($fruits, array($this, "sort_by_weight"));
andyk
New php-forum User
New php-forum User
 
Posts: 2
Joined: Sun May 12, 2013 5:20 am

Re: Can't get usort working

Postby Strider64 » Sun May 12, 2013 7:31 am

From the php.net manual - "uasort — Sort an array with a user-defined comparison function and maintain index association."
I just initialized the array that way, so I could visualize it better (It's the same thing). I didn't write it in a class, but I think this might help you?

Code: Select all
<?php     
   
    $fruits = array(
       0 => array('fruit' => 'apple', 'weight' => 3),
       1 => array('fruit' => 'pineapple', 'weight' => 1),
       2 => array('fruit' => 'orange', 'weight' => 2),
       3 => array('fruit' => 'pear', 'weight' => 4)
    );
   
    // Name sorting function:
    function name_sort($x, $y) {
       return strcasecmp($x['fruit'], $y['fruit']);
    }
   
    // Weight sorting function:
    function sort_by_weight($x, $y) {
      return ($x['weight'] < $y['weight']);   
    }
   
    // Print the array as is:
    echo '<h2>Array As Is</h2><pre>' . print_r($fruits, 1) . '</pre>';
   
    // Sort by name:   
    uasort($fruits, 'name_sort');
    echo '<h2> Array Sorted by Name</h2><pre>' . print_r($fruits, 1) . '</pre>';
 
     // Sort by weight:   
    uasort($fruits, 'sort_by_weight');
    echo '<h2> Array Sorted by Weight</h2><pre>' . print_r($fruits, 1) . '</pre>';
User avatar
Strider64
New php-forum User
New php-forum User
 
Posts: 57
Joined: Sat Mar 23, 2013 8:24 am


Return to PHP coding => General

Who is online

Users browsing this forum: No registered users and 3 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.