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);
Related
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 6 years ago.
i have the following array and i want to sort this array in descending order on the base of the "count" index value in php. i have used the following code but it is not working for me. please give me hint to sort array in descending order.
Array:-
Array ( [0] => Array ( [text] => this is text [count] => 0 )
[1] => Array ( [text] => this is second text [count] => 2 )
[2] => Array ( [text] => this is third text [count] => 1 )
)
I have tried the following code.
function sort_count($a, $b) {
return $a['count'] - $b['count'];
}
$sorted_array = usort($array, 'sort_count');
Ascending..
usort($your_array, function($a, $b) {
return $a['count'] - $b['count'];
});
Descending..
usort($your_array, function($a, $b) {
return $b['count'] - $a['count'];
});
Example here
Try this:
Note: Checking your equality acts as an added advantage.
function sort_count($a, $b) {
if ($a['count'] === $b['count']) {
return 0;
} else {
return ($a['count'] > $b['count'] ? 1:-1);
}
}
$sorted_array = usort($array, 'sort_count');
echo "<pre>";
print_r($array);
echo "</pre>";
Hope this helps.
you can use core php functions like
rsort ($array)
arsort($array)
also you should read this in php manual
http://php.net/manual/en/array.sorting.php
Here is the solution:
$a1 = array (array ( "text" => "this is text", "count" => 0 ),
array ( "text" => "this is text", "count" => 1 ),
array ( "text" => "this is text", "count" => 2 ),
);
usort($a1 ,sortArray('count'));
function sortArray($keyName) {
return function ($a, $b) use ($keyName) {return ($a[$keyName]< $b[$keyName]) ? 1 : 0;
};
}
print_r($a1);
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)
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);
?>
i've got a PHP script where i rearange a multidimensional array with the use of the usort()-function.
this is a sample array (print_r-output) of array $arr
Array
(
[3] => Array
(
[name] => Bjudningen
[grade] => 5
[grade_type] => calculated
[orgname] => LInvitation
[id] => 13975
)
[0] => Array
(
[name] => Coeur fidèle
[grade] => 3
[grade_type] => calculated
[orgname] => Coeur fidèle
[id] => 8075
)
[2] => Array
(
[name] => Dawsonpatrullen
[grade] => 5
[grade_type] => calculated
[orgname] => The Dawson Patrol
[id] => 13083
)
)
And this is my PHP script
function sort_movies($arr,$val){
function cmp($x, $y)
{
if ( $x[$val] == $y[$val] )
return 0;
else if ( $x[$val] < $y[$val] )
return -1;
else
return 1;
}
usort($arr, 'cmp');
return $arr;
}
$sorted = sort_movies($arr,"grade");
I want to be able to sort the array on different subkeys (i.e. name, grade,id), but it doesn't work the way i do it above. however if i change $val in the sort movies function to the value "grade" it does work, so for some reason it won't allow me to send in a vaiable as the sort parameter.
what is it i'm doing wrong?
May be try this by send index of subkey i.e. grade instead of name of subkey .
With 5.3 you can do it like this:
function create_sort($key)
{
return function($x,$y) use($key)
{
return $x[$key] - $y[$key];
};
}
$sorter = create_sort('name');
usort($arr, $sorter);
The problem is that $val is only available within the scope of the function sort_movies(), not in the scope of cmp(). You need to just declare it as global. This will pull it into scope so you can use it within the cmp() function.
function sort_movies($arr,$val){
function cmp($x, $y)
{
global $val; // <---------------------------------
if ( $x[$val] == $y[$val] )
return 0;
else if ( $x[$val] < $y[$val] )
return -1;
else
return 1;
}
usort($arr, 'cmp');
return $arr;
}
$sorted = sort_movies($arr,"grade");
http://php.net/manual/en/language.variables.scope.php
I have the following array
[0] => Array
(
[id] => 229
[val] => 2
)
[3] => Array
(
[id] => 237
[val] => 1
)
[4] => Array
(
[id] => 238
[val] => 6
)
I need to sort this array according to the val values in the array, and do not know how to accomplish this?
function cmp($a, $b)
{
if ($a["val"] == $b["val"]) {
return 0;
}
return ($a["val"] < $b["val"]) ? -1 : 1;
}
usort($yourarray, "cmp");
Read this for more information.
array_multisort can help with this, example 3 presents a similar problem and solution.
This would help - http://www.informit.com/articles/article.aspx?p=341245&seqNum=7
You can use array_multisort()
Examples here: http://www.php.net/manual/en/function.array-multisort.php
The Example #3 Sorting database results is what you want. Might be easier if you are not familiar with callback functions and usort().
use this function to sort array accroding to your need
function sksort(&$array, $subkey="id",$sort_ascending=false)
{
if (count($array))
$temp_array[key($array)] = array_shift($array);
foreach($array as $key => $val){
$offset = 0;
$found = false;
foreach($temp_array as $tmp_key => $tmp_val)
{
if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
{
$temp_array = array_merge(
(array)array_slice($temp_array,0,$offset),
array($key => $val),
array_slice($temp_array,$offset)
);
$found = true;
}
$offset++;
}
if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
}
if ($sort_ascending) $array = array_reverse($temp_array);
else $array = $temp_array;
}
==========================================================================
now use this function in ur array
sksort($arrayname, "val"); /* for ascending */
sksort($arrayname, "val", true); /* for descending */