PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
Ollie Saunders
DevNet Master
Posts: 3179 Joined: Tue May 24, 2005 6:01 pm
Location: UK
Post
by Ollie Saunders » Thu Jan 11, 2007 6:32 pm
I want to sort an array where:
numeric keys appear first sorted by their values
associative keys appear second sorted by their key only
For instance
Code: Select all
array(
'foo' => 1,
'bar' => 2,
0 => 'g',
'zim' => 4,
1 => 'a'
);becomes
Code: Select all
array(
0 => 'a',
1 => 'g',
'bar' => 2,
'foo' => 1,
'zim' => 4);I tried this initially
Code: Select all
asort($array, SORT_STRING);
ksort($array, SORT_STRING);but the second call just undoes the good work done by the first.
Kieran Huggins
DevNet Master
Posts: 3635 Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:
Post
by Kieran Huggins » Thu Jan 11, 2007 7:05 pm
You're on the right track - you just need to save the appropriate results of each sort:
Code: Select all
$a = array(
'foo' => 1,
'bar' => 2,
0 => 'g',
'zim' => 4,
1 => 'a'
);
asort($a);
foreach($a as $key=>$val) if(is_numeric($key)) $output[]=$val;
ksort($a);
foreach($a as $key=>$val) if(!is_numeric($key)) $output[$key]=$val;
Kieran Huggins
DevNet Master
Posts: 3635 Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:
Post
by Kieran Huggins » Fri Jan 12, 2007 4:39 am
It seems your problems are the most fun these days - it should be me thanking you!
Just how much a post-whore do I have to become to shed this "Forum Contributor" status anyhow? My fingers are crossed that it will be gone by lunch (500 posts).
Ollie Saunders
DevNet Master
Posts: 3179 Joined: Tue May 24, 2005 6:01 pm
Location: UK
Post
by Ollie Saunders » Fri Jan 12, 2007 4:52 am
Sorry to disappoint . It takes time. You seem to be racking them up really fast though. Much faster than me. Do you actually get any work done?
Kieran Huggins
DevNet Master
Posts: 3635 Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:
Post
by Kieran Huggins » Fri Jan 12, 2007 5:08 am
...in theory. Tasks are performed
I guess "Contributor" is better than "Devnet @$$clown" and "Devnet @sshat"
And by the time I hit 1000 my girlfriend will definitely agree with "junkie"!
Edit:
page three insists I'll be more "Regular" than "Junkie".... and on that note: I have to go to the washroom.
Jenk
DevNet Master
Posts: 3587 Joined: Mon Sep 19, 2005 6:24 am
Location: London
Post
by Jenk » Fri Jan 12, 2007 6:14 am
I half finished my reply before noticing the problem is already solved:
Code: Select all
<?php
$num = $assoc = array();
foreach ($array as $key => $val)
{
if (is_numeric($key)) $num[$key] = $val;
else $assoc[$key] = $val;
}
sort($num);
ksort($assoc);
$array = $num + $assoc;
?>