Ok I have the following array:
Array
(
[0] => Array
(
[id] => 6
[name] => This Course
[time] => 1288082700
[description] => blah blah .
[link] => http://this.com/?g=5
[course] => 22
)
[1] => Array
(
[id] => 2
[name] => Workshop
[time] => 1287561600
[description] => This description
[link] => http://this.com/?g=5
[session] => 8
[course] => 23
[type] => standard
[adobelink] =>
)
)
How can I sort this entire array by using the inner 'time' key ?
Thanks!
You can use the usort function as:
function cmp($a,$b) {
return $a['time'] - $b['time'];
}
usort($arr,'cmp');
Working link
Use usort():
This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
Example:
function cmp($a, $b) {
if ($a['time'] == $b['time']) {
return 0;
}
return ($a['time'] < $b['time']) ? -1 : 1;
}
usort($array, 'cmp');
Of course this will fail if an array has no time element. What should happen then depends on your requirements so I will leave the error handling to you ;)
Use PHP usort() function: http://php.net/manual/en/function.usort.php
First, define a function that will decide on compare result for your data structure:
function cmp($a, $b)
{
if ($a['time'] == $b['time']) {
return 0;
}
return ($a['time'] < $b['time']) ? -1 : 1;
}
Then call usort() and give the nmae of your function to it:
usort($array, "cmp");
You're done!
uasort() will maintain your keys1.
uasort($a, function($a, $b) {
$a = $a['time']; // Assuming keys exist
$b = $b['time'];
if ($a == $b) {
return 0;
} else {
return $a < $b ? -1 : 1; // Reverse < if sort order is wrong
}
});
Anonymous function syntax requires PHP 5.3+! Pass the name of the comparison function if <5.3 (see other answers).
1) In case you care about the keys, too. If not, just use the usort() approach found in abundance above :) The comparison function are basically identical (except for #codaddict's elegant approach).
http://dk.php.net/usort
function sortByTime($a, $b)
{
if ($a['time'] > $b['time'])
{
return 1;
}
else if ($a['time'] < $b['time'])
{
return -1;
}
return 0;
}
usort($yourArray, 'sortByTime');
Related
I want to sort this array by year:
Array
(
[0] => data/pictures/alice/1980
[1] => data/pictures/alice/1985
[2] => data/pictures/bob/1981
[3] => data/pictures/bob/1985
[4] => data/pictures/bob/1987
[5] => data/pictures/bob/1989
)
Expected result:
Array
(
[0] => data/pictures/alice/1980
[1] => data/pictures/bob/1981
[2] => data/pictures/alice/1985
[3] => data/pictures/bob/1985
[4] => data/pictures/bob/1987
[5] => data/pictures/bob/1989
)
I've already tried different sort functions without success.
Example:
asort($paths, SORT_STRING | SORT_FLAG_CASE);
sort($path, SORT_NUMERIC);
Since it's a path just map the array through basename() and then sort based on that:
array_multisort(array_map('basename', $paths), SORT_ASC, $paths);
Try this
function cmp($a, $b) {
// if equal, don't do much
if ($a == $b) {
return 0;
}
$explodedA = explode('/', $a);
$explodedB = explode('/', $b);
$yearPartA = $explodedA[count($explodedA) - 1];
$yearPartB = $explodedB[count($explodedB) - 1];
if ($explodedPartA == $explodedPartB) { // compare full string
return ($a < $b) ? -1 : 1;
}
return ($yearPartA < $yearPartB) ? -1 : 1;
}
// actual sort of the array $path (e.g. the whole point)
usort($path, "cmp");
Consider, however that you'd probably be doing 'explode' several times for each array element and that it might be cheaper to work a bit on the array first. Not sure how big your array is... Do some testing.
$array = ['data/pictures/alice/1980','data/pictures/alice/1985','data/pictures/bob/1981','data/pictures/bob/1985','data/pictures/bob/1987','data/pictures/bob/1989'];
uasort($array, function($a,$b) {
$y1 = array_pop(explode('/', $a));
$y2 = array_pop(explode('/', $b));
if($y1===$y2) {
// if year the same use other criteria
if($a===$b) {
return 0;
}
return $a>$b?-1:1;
};
return $y1>$y2?-1:1;
});
Use usort and in the custom function explode the strings by "/" and compare the last parts of the arrays.
This should be really simple, but what is the way to go on this.
I want to sort an multidimensional array by a key, like this:
Array (
[0] => Array
(
[iid] => 1
[invitee] => 174
[nid] => 324343
[showtime] => 2010-05-09 15:15:00
[location] => 13
[status] => 1
[created] => 2010-05-09 15:05:00
[updated] => 2010-05-09 16:24:00
)
[1] => Array
(
[iid] => 1
[invitee] => 220
[nid] => 21232
[showtime] => 2010-05-09 15:15:00
[location] => 12
[status] => 0
[created] => 2010-05-10 18:11:00
[updated] => 2010-05-10 18:11:00
))
Say i want to sort this by [status], how would I achieve this?
Thanks in advance!
//define a comparison function
function cmp($a, $b) {
if ($a['status'] == $b['status']) {
return 0;
}
return ($a['status'] < $b['status']) ? -1 : 1;
}
usort($array, "cmp");
That should do what you want, you can alter the comparison function to sort on whatever key you want.
Try this : Using array_multisort
$sort = array();
foreach($your_array as $k=>$v) {
$sort['status'][$k] = $v['status'];
}
array_multisort($sort['status'], SORT_DESC, $your_array);
echo "<pre>";
print_r($your_array);
Ref: http://php.net/manual/en/function.array-multisort.php
usort function is what you're looking for:
<?php
function cmp($a, $b) {
return $b["status"] - $a["status"];
}
$sorted = usort($your_array, "cmp");
var_dump($sorted);
?>
Try this
function cmp_by_status($a, $b)
{
if ($a['status'] == $b['status']) {
return 0;
}
return ($a['status'] < $b['status') ? -1 : 1;
}
usort($data_array, "cmp_by_status");
I have added this answer at Sort multi-dimensional array by specific key sort the array specific key to sorting array value.
function sortBy($field, &$array, $direction = 'asc')
{
usort($array, create_function('$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b)
{
return 0;
}
return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
'));
return true;
}
Call this function by specific array key
sortBy('status', $array);
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 7 years ago.
I have an array like one mentioned below
Array
(
[6] => Array
(
[name] => Extras
[total_products] => 0
[total_sales] => 0
[total_affiliation] => 0
)
[5] => Array
(
[name] => Office Products
[total_products] => 7
[total_sales] => 17
[total_affiliation] => 8
)
[1] => Array
(
[name] => Hardware Parts
[total_products] => 6
[total_sales] => 0
[total_affiliation] => 0
)
)
Right now, order is: Extras, Office Products, Hardware Parts
I want to sort main array in such as way that it is order by total_sales of inner-array in desc order
so order will be: Office Products, Extras, Hardware Parts
Any help guys
PHP 5.3:
usort($array, function ($a, $b) { return $b['total_sales'] - $a['total_sales']; });
PHP 5.2-:
usort($array, create_function('$a,$b', 'return $b["total_sales"] - $a["total_sales"];'));
Use a custom function and usort:
<?php
function custom_sale_sort($a, $b)
{
if ($a['total_sales'] < $b['total_sales'])
return 1;
elseif ($a['total_sales'] == $b['total_sales'])
return 0;
else
return -1;
}
usort($array, 'custom_sale_sort');
If you need your array sorted in the other direction, then switch the (1,-1) values around in the custom function.
Here is the class you can use to do multidimension sort
Note: You must have PHP5
class MultiDimensionSort
{
const ASCENDING = 0,DESCENDING = 1;
public $sortColumn,$sortType;
public function __construct($column = 'price', $type = self::ASCENDING)
{
$this->column = $column;
$this->type = $type;
}
public function cmp($a, $b)
{
switch($this->type)
{
case self::ASCENDING:
return ($a[$this->column] == $b[$this->column]) ? 0 : (($a[$this->column] < $b[$this->column]) ? -1 : 1);
case self::DESCENDING:
return ($a[$this->column] == $b[$this->column]) ? 0 :(($a[$this->column] < $b[$this->column]) ? 1 : -1);
default:
assert(0); // unkown type
}
}
}
Like you have array named summary with contain above array. than you can do sort by following statements.
// assuming your array variable is $summary
$s = new MultiDimensionSort('total_sales', MultiDimensionSort::DESCENDING); // sort by total_sales
usort($summary, array($s, 'cmp'));
print"<pre>";print_r($summary);
Cheers!
May be this ll help you
I have a data structure that looks like
Array
(
[0] => Array
(
[0] => something
[1] => 1296986500
)
[1] => Array
(
[0] => something else
[1] => 1296600100
)
[2] => Array
(
[0] => another thing
[1] => 1296831265
)
)
I'm trying to sort the array based off of the integer which is a unix timestamp. The following function looks right to me but is not sorting the way I want.
function cmp($a, $b)
{
if ($a[1] == $b[1]) {
return 0;
}
return ($a[1] < $b[1]) ? -1 : 1;
}
NOTE
when calling this function within a class the OO syntax is the following
uasort($_data, array($this, 'cmp'));
That sorts your timestamps in ascending order; for descending order, flip the second comparison (i.e. change $a[1] < $b[1] to $a[1] > $b[1]):
function cmp($a, $b)
{
if ($a[1] == $b[1]) {
return 0;
}
return ($a[1] > $b[1]) ? -1 : 1;
}
You can setup time stamp as pivot. And use array_multisort().
<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
$time[$key] = $row[1]; //unix timestamp
}
array_multisort( $time, SORT_ASC, $data);
?>
This should be really simple, but what is the way to go on this.
I want to sort an multidimensional array by a key, like this:
Array (
[0] => Array
(
[iid] => 1
[invitee] => 174
[nid] => 324343
[showtime] => 2010-05-09 15:15:00
[location] => 13
[status] => 1
[created] => 2010-05-09 15:05:00
[updated] => 2010-05-09 16:24:00
)
[1] => Array
(
[iid] => 1
[invitee] => 220
[nid] => 21232
[showtime] => 2010-05-09 15:15:00
[location] => 12
[status] => 0
[created] => 2010-05-10 18:11:00
[updated] => 2010-05-10 18:11:00
))
Say i want to sort this by [status], how would I achieve this?
Thanks in advance!
//define a comparison function
function cmp($a, $b) {
if ($a['status'] == $b['status']) {
return 0;
}
return ($a['status'] < $b['status']) ? -1 : 1;
}
usort($array, "cmp");
That should do what you want, you can alter the comparison function to sort on whatever key you want.
Try this : Using array_multisort
$sort = array();
foreach($your_array as $k=>$v) {
$sort['status'][$k] = $v['status'];
}
array_multisort($sort['status'], SORT_DESC, $your_array);
echo "<pre>";
print_r($your_array);
Ref: http://php.net/manual/en/function.array-multisort.php
usort function is what you're looking for:
<?php
function cmp($a, $b) {
return $b["status"] - $a["status"];
}
$sorted = usort($your_array, "cmp");
var_dump($sorted);
?>
Try this
function cmp_by_status($a, $b)
{
if ($a['status'] == $b['status']) {
return 0;
}
return ($a['status'] < $b['status') ? -1 : 1;
}
usort($data_array, "cmp_by_status");
I have added this answer at Sort multi-dimensional array by specific key sort the array specific key to sorting array value.
function sortBy($field, &$array, $direction = 'asc')
{
usort($array, create_function('$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b)
{
return 0;
}
return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
'));
return true;
}
Call this function by specific array key
sortBy('status', $array);