Page 1 of 1

Sort an array using key and value

Posted: Thu Jan 11, 2007 6:32 pm
by Ollie Saunders
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.

Posted: Thu Jan 11, 2007 6:59 pm
by feyd
I don't think you're going to find a solution using just the sort sibling functions.

I'm thinking.. array_keys(), array_filter(), array_values() and/or some fancy dancing with array_multisort()

Posted: Thu Jan 11, 2007 7:05 pm
by Kieran Huggins
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;

Posted: Fri Jan 12, 2007 4:01 am
by Ollie Saunders
Worked Kieran thanks....again.

Posted: Fri Jan 12, 2007 4:39 am
by Kieran Huggins
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).

Posted: Fri Jan 12, 2007 4:52 am
by Ollie Saunders
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? :D

Posted: Fri Jan 12, 2007 5:08 am
by Kieran Huggins
...in theory. Tasks are performed :wink:

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.

Posted: Fri Jan 12, 2007 6:14 am
by Jenk
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;

?>
:)