peace_love
peace_love

Reputation: 6461

How can I sort one array by the values of another array?

My array $a defines the sorting of my elements:

array:4 [▼
  "rabbit" => "201"
  "cat" => "0"
  "monkey" => "100"
  "horse" => "0"
]

array $b defines a number:

array:4 [▼
  "rabbit" => "9144"
  "cat" => "10244"
  "monkey" => "10068"
  "horse" => "9132"
]

I try to sort now the numbers by the sorting element. The result I am looking for is:

   array:4 [▼
      1 => "9144"
      2 => "10068"
      3 => "10244"
      4 => "9132"
    ]

I try to achieve this with "array_combine":

  $c=array_combine($a,$b);
  krsort($c);

But because of the zero I am loosing one element:

array:3 [▼
  201 => "9144"
  100 => "10068"
  0 => "9132"
]

Upvotes: 0

Views: 56

Answers (2)

Progrock
Progrock

Reputation: 7485

You can sort a copy of the first, keeping the associated keys. With asort. And then just loop that and build a new array with the mapped values from b.

<?php

$a = [
  "rabbit" => "201",
  "cat" => "0",
  "monkey" => "100",
  "horse" => "0"
];

$b = [
  "rabbit" => "9144",
  "cat" => "10244",
  "monkey" => "10068",
  "horse" => "9132"
];

$sort_order = $a;
asort($sort_order, SORT_DESC);
$i = 1;
foreach($sort_order as $k => $v)
    $result[$i++] = $b[$k];

var_dump($result);

Output:

array(4) {
    [1]=>
    string(5) "10244"
    [2]=>
    string(4) "9132"
    [3]=>
    string(5) "10068"
    [4]=>
    string(4) "9144"
  }

Upvotes: 1

deceze
deceze

Reputation: 522042

You want something along these lines:

uksort($b, function ($i, $j) use ($a) {
    return $a[$i] <=> $a[$j];
});

This sorts $b by its keys, and the key values are translated to the numeric values in $a and compared by those. This even keeps the key-value association in $b; if you want to get rid of the keys you can use array_values() afterwards.

Upvotes: 2

Related Questions