Function to sort array by elements and count of element in PHP

By: oscar  

Function to sort array by elements and count of element (before php 5.3) (not use Lambda Functions, and Closures)



function arraySortByElements($array2sort,$sortField,$order,$iscount=false) {

if ('.($iscount?'true':'false').'){
if(count($a["'.$sortField.'"]) > count($b["'.$sortField.'"])) return 1*'.$order.';
if(count($a["'.$sortField.'"]) < count($b["'.$sortField.'"])) return -1*'.$order.';
if($a["'.$sortField.'"] > $b["'.$sortField.'"]) return 1*'.$order.';
if($a["'.$sortField.'"] < $b["'.$sortField.'"]) return -1*'.$order.';
return 0;';

usort($array2sort, create_function('$a,$b',$functionString));
return $array2sort;


//init Array for testing :
$testArray = array( 
array('name' => 'Lenny', 'note' => 5, 'listId' => array(654,987,32165)), 
array('name' => 'Olivier', 'note' =>3, 'listId' => array(2)), 
array('name' => 'Gregory', 'note' => 1, 'listId' => array(45,58)), 
array('name' => 'Clement', 'note' => 2, 'listId' => array(584,587,741,14781,147))

//sorted Arrays :
$testArrayByNameASC = arraySortByElements($testArray,'name',1);
$testArrayByNoteDESC = arraySortByElements($testArray,'note',-1);
$testArrayByCountlistIdDESC = arraySortByElements($testArray,'listId',-1,true);


Archived Comments

Most Viewed Articles (in PHP )

Function to force strict boolean values in PHP

PHP code to write to a CSV file from MySQL query

Using Text file as database in PHP

unset() and empty() functions in PHP

Polymorphism in PHP

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Encrypting and decrypting in PHP

PHP pages does not display in IIS 6 with Windows 2003

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/ into server:

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Function to sort array by elements and count of element in PHP

Latest Articles (in PHP)

Comment on this tutorial