I have a multidimensional array in php and I want to sort it according to the entered time, but I can't so please give some ideas.
Array
(
[0] => Array
(
[account_id] => 9
[entered] => 1369374812
)
[1] => Array
(
[account_id] => 9
[entered] => 1377587453
)
[2] => Array
(
[account_id] => 9
[entered] => 1373542381
)
[3] => Array
(
[account_id] => 9
[entered] => 1372988725
)
[4] => Array
(
[account_id] => 353
[entered] => 1380191316
)
[5] => Array
(
[account_id] => 9
[entered] => 1377587610
)
)
You can do that with array_multisort
//in PHP 5.5:
$rgOrder = array_column($rgData, 'entered');
array_multisort($rgOrder, SORT_ASC, $rgData);
if you have PHP older than 5.5, then:
$rgOrder = array_map(function($rgItem)
{
return $rgItem['entered'];
}, $rgData);
array_multisort($rgOrder, SORT_ASC, $rgData);
-you can find a fiddle here . If you don't want to use array_multisort
(since it requires to create temporary array first), you can act like:
usort($rgData, function($rgX, $rgY)
{
return $rgX['entered']>$rgY['entered']?-1:$rgX['entered']!=$rgY['entered'];
});
-here's fiddle for it. All samples require at least PHP 5.3. Otherwise you need to use create_function
for callback definitions.
Try this,
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($your_array,"account_id");
You can achieve the sorting using usort
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 0);
function compare($a, $b) {
if ( $a['entered'] == $b['entered'] ) {
return 0;
}
return ( $a['entered'] < $b['entered'] ) ? -1 : 1;
}
$a = array(
array('account_id' => 9, 'entered' => 1369374812),
array('account_id' => 9, 'entered' => 1377587453),
array('account_id' => 9, 'entered' => 1373542381)
);
usort($a, "compare");
print_r($a);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.