Can't get usort working

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Post Reply
User avatar
Strider64
php-forum Active User
php-forum Active User
Posts: 267
Joined: Sat Mar 23, 2013 8:24 am

Re: Can't get usort working

Post by 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>';

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 1 guest