In case you need to sort an associative array by one of its keys, this function might be useful:
<?php
function sortByOneKey(array $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
}
else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
?>
Consider the following example:
<?php
$users = array(
1 => array('name' => 'John', 'age' => 35),
2 => array('name' => 'Alice', 'age' => 23),
3 => array('name' => 'Bob', 'age' => 26)
);
$sortedByNameAsc = sortByOneKey($users, 'name');
$sortedByNameDesc = sortByOneKey($users, 'name', false);
echo "Sorted by Name in ascending order: ";
echo "<pre>" . print_r($sortedByNameAsc, true) . "</pre>";
echo "<br /><br />Sorted by Name in descending order: ";
echo "<pre>" . print_r($sortedByNameDesc, true) . "</pre>";
?>
The output will be the following:
Sorted by Name in ascending order:
Array
(
[2] => Array
(
[name] => Alice
[age] => 23
)
[3] => Array
(
[name] => Bob
[age] => 26
)
[1] => Array
(
[name] => John
[age] => 35
)
)
Sorted by Name in descending order:
Array
(
[1] => Array
(
[name] => John
[age] => 35
)
[3] => Array
(
[name] => Bob
[age] => 26
)
[2] => Array
(
[name] => Alice
[age] => 23
)
)
Monday, 14 May 2012
sort an associative array by one of its keys
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment