4

There are 2 arrays, both with the same length and with the same keys:

$a1 = [1=>2000,65=>1354,103=>1787];
$a2 = [1=>'hello',65=>'hi',103=>'goodevening'];

asort($a1);

The keys of a1 and a2 are id's from a database.

a1 gets sorted by value. Once sorted, how can we use the same sorting order in a2?

Thanks!

DADU
  • 6,482
  • 7
  • 42
  • 64

4 Answers4

5

I believe this works:

$a1 = array(1=>2000,65=>1354,103=>1787);
$a2 = array(1=>'hello',65=>'hi',103=>'goodevening');

asort($a1); // sort $a1, maintaining array index

// sort $a2 by key, using the order of $a1
function my_uksort($a, $b) {
    global $a1;

    return $a1[$a] < $a1[$b] ? -1 : 1;
}
uksort($a2, 'my_uksort');

var_dump($a1);
var_dump($a2);
Annika Backstrom
  • 13,937
  • 6
  • 46
  • 52
  • Thanks! This seems to work great. I prefer the use of a custom sort function over using foreach. – DADU Apr 21 '10 at 17:42
1

Not optimal maybe.. but it's short:

$a1 = array(1=>2000,65=>1354,103=>1787);
$a2 = array(1=>'hello',65=>'hi',103=>'goodevening');
asort($a1);

foreach(array_keys($a1) as $i) $out[$i] = $a2[$i];

echo join("\n", $out);

look into uasort() also

MSpreij
  • 1,142
  • 13
  • 20
0

You probably want to look at array_multisort() if you can handle losing ID association (arrays will be re-indexed).

array_multisort($a1, $a2);
Karol J. Piczak
  • 585
  • 1
  • 5
  • 24
  • I can't handle losing key association since this forms the relation between the two arrays. – DADU Apr 21 '10 at 17:24
  • The relation will be left intact. The question is if you use those real (database) IDs somewhere later on. If you need them, then there's no way to do it in one call (see: http://php.net/manual/en/array.sorting.php). Just use a custom user sort function as presented in other answers. – Karol J. Piczak Apr 21 '10 at 17:36
0
foreach($a1 as $key => $value){
   //do something with $a2
   echo $a2[$key];
}
munch
  • 6,311
  • 4
  • 23
  • 27
  • So there is no way of doing this with a built-in PHP function? – DADU Apr 21 '10 at 17:21
  • @marbrun: You can use a few built-in PHP functions to get it to work. I just find this to be a whole lot easier. AFAIK, there isn't one function that would do it for you and still maintain key associations – munch Apr 21 '10 at 17:34