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)
<?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);
?>
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
PHP convert string to lower case
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8