Here we will learn how we can sort two dimensional array:-
lets take an example :-
<?php
$activities = array (
'1' => array(
'id' => 1,
'time' => "2015-10-22 14:20:00"
),
'2' => array(
'id' => 2,
'time' => "2015-09-15 22:20:00"
),
'3' => array(
'id' => 1,
'time' => "2015-01-25 22:20:00"
)
);
echo 'Before Sorting <br>';
echo '<pre>';
print_r($activities);
echo '</pre>';
?>
run this code in the browser.
So now above array we will sort by time key,
<?php
function multid_sort($arr, $index) {
$b = array();
$c = array();
foreach ($arr as $key => $value) {
$b[$key] = $value[$index];
}
asort($b);
foreach ($b as $key => $value) {
$c[] = $arr[$key];
}
return $c;
}
$sorted_act = multid_sort($activities, 'time');
echo 'After Sorting <br>';
echo '<pre>';
print_r($sorted_act);
echo '</pre>';
?>
Now run the above code in browser, you will see the output below :-
Before Sorting
Array
(
[1] => Array
(
[id] => 1
[time] => 2015-10-22 14:20:00
)
[2] => Array
(
[id] => 2
[time] => 2015-09-15 22:20:00
)
[3] => Array
(
[id] => 1
[time] => 2015-01-25 22:20:00
)
)
After Sorting
Array
(
[0] => Array
(
[id] => 1
[time] => 2015-01-25 22:20:00
)
[1] => Array
(
[id] => 2
[time] => 2015-09-15 22:20:00
)
[2] => Array
(
[id] => 1
[time] => 2015-10-22 14:20:00
)
)
Enjoy the code :)
0 Comment(s)