note 71424 added to function.sort
| From: | crudo at pinknet dot cz | Date: | Tue, 28 Nov 2006 13:54:52 +0000 |
| Subject: | note 71424 added to function.sort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120125@lists.php.net to get a copy of this message | ||
Simple way, how to sort an array without loosing keys:
<?php
$sizes = $bad = $good = array("d" => "dddd", "a" =>
"aaaa", "c" => "cccc", "e" => "eeee",
"b" => "bbbb");
// original
print_r($sizes);
/*
Array
(
[d] => dddd
[a] => aaaa
[c] => cccc
[e] => eeee
[b] => bbbb
)
*/
// bad way
sort($bad);
print_r($bad);
/*
Array
(
[0] => aaaa
[1] => bbbb
[2] => cccc
[3] => dddd
[4] => eeee
)
*/
// good way
$good=array_flip($good);
ksort($good);
$good=array_flip($good);
print_r($good);
/*
Array
(
[a] => aaaa
[b] => bbbb
[c] => cccc
[d] => dddd
[e] => eeee
)
*/
?>
----
Server IP: 147.32.160.17
Probable Submitter: 62.44.5.18
----
Manual Page -- http://www.php.net/manual/en/function.sort.php
Edit -- https://master.php.net/note/edit/71424
Del: integrated -- https://master.php.net/note/delete/71424/integrated
Del: useless -- https://master.php.net/note/delete/71424/useless
Del: bad code -- https://master.php.net/note/delete/71424/bad+code
Del: spam -- https://master.php.net/note/delete/71424/spam
Del: non-english -- https://master.php.net/note/delete/71424/non-english
Del: in docs -- https://master.php.net/note/delete/71424/in+docs
Del: other reasons-- https://master.php.net/note/delete/71424
Reject -- https://master.php.net/note/reject/71424
Search -- https://master.php.net/manage/user-notes.php