Help me sort this php array using usort() - php

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);
?>

Related

Not getting how to sort multidimensional array by a specific key in php [duplicate]

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);

Sort array by sub array

I have array:
$array = array(array('2012-12-12', 'vvv'), array('2012-12-14', 'df'),array('2012-12-10', 'vvv'),array('2012-12-11', 'vvv'));
Array
(
[0] => Array
(
[0] => 2012-12-12
[1] => vvv
)
[1] => Array
(
[0] => 2012-12-14
[1] => df
)
[2] => Array
(
[0] => 2012-12-10
[1] => vvv
)
[3] => Array
(
[0] => 2012-12-11
[1] => vvv
)
)
http://codepad.org/gxw2yKMU
is possible to sort this with dates DESC? For this example should be:
$array[1] //2012-12-14
$array[0] //2012-12-12
$array[3] //2012-12-11
$array[2] //2012-12-10
For me the best way is use embedded functions for PHP, but how? :)
You can use usort with a custom function. If you're on PHP < 5.3 you'll need a named function rather than, as I have, an anonymous one.
$array = array(
array('2012-12-12', 'vvv'),
array('2013-12-14', 'df'),
array('2012-12-14', 'df'),
array('2012-12-10', 'vvv'),
array('2012-12-11', 'vvv')
);
usort($array, function($a, $b) {
if ($a[0] == $b[0]) return 0;
return ($a > $b) ? -1 : 1;
});
print_r($array);
You should be able to use usort
usort( $array, 'sortFunction' );
function sortFunction( $a, $b ) {
if( $a[0] == $b[0] )
return 0;
return ( $a[0] > $b[0] ? return -1 : 1 );
}
You can use array_multisort() :
foreach ($array as $key => $row) {
$dates[$key] = $row[0];
}
array_multisort($dates, SORT_DESC, $array);
First, you put out all dates in a new array. Then, array_multisort() will sort the second array ($array) in the same order than the first ($dates)

Array sort in PHP

How can I sort a 2D array in PHP.
I want to sort on date, Array is in this format :
[result] => Array
(
[0] => Array
(
[link] => http://local/node/0
[date] => 13158505310
)
[1] => Array
(
[link] => http://local/node/1
[date] => 13158505311
)
[2] => Array
(
[link] => http://local/node/2
[date] => 13158505312
Use usort:
usort( $array, function( $a, $b ){ return $a["date"] - $b["date"]; } );
Use this
function sortByDateDesc($a, $b) {
return strcmp($a["date"], $b["date"]);
}
function sortByDateAsc($a, $b) {
if ($a['date'] == $b['date']) {
return 0;
}
return ($a['date'] > $b['date']) ? -1 : 1;
}
usort($array, 'sortByDateDesc'); //Descending order
//usort($array, 'sortByDateAsc'); //Asceding order
Use http://nl.php.net/manual/en/function.usort.php
You could also try multisort http://www.php.net/manual/en/function.array-multisort.php
may be this code helpful to you....
// Obtain a list of columns
foreach (data as key => row) {
links[key] = row['link'];
dates[key] = row['date'];
}
// Sort the data with link descending, date ascending
// Add $data as the last parameter, to sort by the common key
array_multisort(link, SORT_DESC, date, SORT_ASC, data);

PHP Array sorting using child nodes?

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');

How to sort a multidimensional array by a certain key?

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);

Categories