Programming Tutorials

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

By: oscar in PHP Tutorials on 2011-04-06  

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

<?php
//-----------------------------
function arraySortByElements($array2sort,$sortField,$order,$iscount=false) {
$functionString='
if ('.($iscount?'true':'false').'){
if(count($a["'.$sortField.'"]) > count($b["'.$sortField.'"])) return 1*'.$order.';
if(count($a["'.$sortField.'"]) < count($b["'.$sortField.'"])) return -1*'.$order.';
}else{
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);
?>





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)