Reputation: 49
I have a complex array that has been generated and I'm trying to sort it by ['file_date']
. Descending. Here it is:
Array (
['images'] => Array (
['93-1138446.jpg'] => Array (
['file_title'] => '93-1138446',
['file_path'] => 'gallery-images-1435/93-1138446.jpg',
['thumb_path'] => 'resources/cache/275x275-75-d3cc92863d4f10bb6cf733159689a0e660fe5847df52beb531fa45b584876f0b.jpg',
['file_date'] => '1497471649'
),
['93-8315415.jpg'] => Array (
['file_title'] => '93-8315415',
['file_path'] => 'gallery-images-1435/93-8315415.jpg',
['thumb_path'] => 'resources/cache/275x275-75-76a8495b1514b8385f090381edf21f64a6c71d2f15c14e0eadabbfce2824fe9a.jpg',
['file_date'] => '1497471650'
),
['94-1234.jpg'] => Array (
['file_title'] => '94-1234',
['file_path'] => 'gallery-images-1435/94-1234.jpg',
['thumb_path'] => 'resources/cache/275x275-75-6e20bd7f6644db1c0fa36600d2aa298b6a5d11e578113f9015fd90dc6b7390e5.jpg',
['file_date'] => '1497470721'
)
)
);
Thank you.
Upvotes: 1
Views: 226
Reputation: 28559
You can use usort(), live demo
usort($array['images'], function($a, $b){return $b['file_date'] - $a['file_date'];});
print_r($array);
Upvotes: 1
Reputation: 1703
Try this function for three dimensional array only.
function array_sort($array, $on, $order=SORT_ASC){
$new_array = array();
$sortable_array = array();
$flag=false;
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if (is_array($v2)) {
foreach ($v2 as $k3 => $v3) {
if ($k3 == $on) {
$flag=true;
$sortable_array[$k][$k2] = $v2;
}
}
}
}
} else {
$sortable_array[$k] = $v;
}
switch ($order) {
case SORT_ASC:
isset($sortable_array[$k])?asort($sortable_array[$k]):'';
break;
case SORT_DESC:
isset($sortable_array[$k])?arsort($sortable_array[$k]):'';
break;
}
}
}
return $flag===false?$array:$sortable_array;
}
Usage Example,
$array = array();
$array['images']['93-8315415.jpg']['file_title']='93-8315415';
$array['images']['93-8315415.jpg']['file_date']='2';
$array['images']['94-1234.jpg']['file_title']='94-1234';
$array['images']['94-1234.jpg']['file_date']='3';
$array['images']['93-1138446.jpg']['file_title']='93-1138446';
$array['images']['93-1138446.jpg']['file_date']='1';
$array['images']['94-12345.jpg']['file_title']='94-12345';
$array['images']['94-12345.jpg']['file_date']='4';
// Ascending sort.
echo "<pre>";
print_r(array_sort($array,'file_date'));
// Descending sort.
echo "<pre>";
print_r(array_sort($array,'file_date',SORT_DESC));
Upvotes: 0