Reputation: 15007
For an instance you have an array:
$unsorted = array(
'desert' => array(
'time' => '1339902235',
'name' => 'desert.jpg'
),
'sea' => array(
'time' => '1339900801',
'name' => 'sea.jpg'
),
'mountain' => array(
'time' => '1339902285',
'name' => 'mountain.jpg'
),
);
Would it be possible to sort the array by the value of $unsorted[$a]['time']
?
Upvotes: 0
Views: 1853
Reputation: 47874
Use modern syntax.
Call uasort()
to perform a custom sort while preserving keys.
Use arrow function syntax to keep the code concise.
Use the 3-way "spaceship" operator to return the appropriate integer value. Comparing $a
values on the left and $b
values on the right will execute an ascending sorting direction.
Code: (Demo)
uasort(
$unsorted,
fn($a, $b) => $a['time'] <=> $b['time']
);
var_export($unsorted);
Upvotes: 0
Reputation: 33996
Note that usort
doesn't preserve keys.
If you need original keys you should use uasort
.
Upvotes: 0
Reputation: 19309
You can using usort
. usort
takes a callback as an argument. Also convert time to integers because that's what they are.
function compare($a,$b) {
if( $a['time'] == $b['time'] ) {
return 0;
}
return (intval($a['time']) < intval($b['time'])) ? -1 : 1;
}
usort( $unsorted, 'compare' );
// $unsorted is now sorted by time
Upvotes: 0
Reputation: 10646
You can use something like usort
and strnatcasecmp
.
For example:
function sort_2d_asc($array, $key) {
usort($array, function($a, $b) use ($key) {
return strnatcasecmp($a[$key], $b[$key]);
});
return $array;
}
function sort_2d_desc($array, $key) {
usort($array, function($a, $b) use ($key) {
return strnatcasecmp($b[$key], $a[$key]);
});
return $array;
}
$unsorted = array(
'desert' => array(
'time' => '1339902235',
'name' => 'desert.jpg'
),
'sea' => array(
'time' => '1339900801',
'name' => 'sea.jpg'
),
'mountain' => array(
'time' => '1339902285',
'name' => 'mountain.jpg'
),
);
$sorted = sort_2d_asc($unsorted, 'time');
Upvotes: 5