0

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"
]

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You might want to multiply the result of the spaceship operator by -1 to have it inverted like the OP wanted.
In that case I'd rather switch $i and $j around… This isn't copy-and-paste ready code by any means obviously and needs to be modified as necessary, but it's showing the way.
Makes more sense.
1

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"
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.