php - Sort associative array by corresponding values in another array from largest to smallest

421

I have 2 arrays. One is the array to re-arrange and the other has elements that define the desired order of the elements. I want to sort the first array by the second array values in a descending order.

{-code-1}

Desired output:

 ['c' => 3, 'b' => 2, 'a' => 1, 'd' => 4]

Effectively:

  • {-code-3} becomes the first element because it relates to10.
  • b => 2 becomes the second element because it realtes to7.
  • a => 1 becomes the third element because it relates to3.
  • d => 4 becomes the fourth element because it relates to1.
329

Answer

Solution:

Right, you want to sort with the other array.

<?php 

    // your arrays
    $array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
    $array2 = array(3, 7, 10, 1);

    //sort using the other array 
    array_multisort($array2, $array);   

    //reverse it (as asked)
    $result = array_reverse($array, true);
    print_r($result); 

?>
711

Answer

Solution:

To sort the first$array according to the mapped numeric values in$array2 in descending order, simply:

  1. callarray_multisort()
  2. write the array to be assessed in the first parameter
  3. write theSORT_DESC flag as the second parameter to implement descending sort order then
  4. write the array which should be affected as the last parameter.

Code: (Demo)

$array = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$array2 = [3, 7, 10, 1];

array_multisort($array2, SORT_DESC, $array);
var_export($array);

Output:

array (
  'c' => 3,
  'b' => 2,
  'a' => 1,
  'd' => 4,
)
721

Answer

Solution:

Just try with:

$array  = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$array2 = array(3, 7, 10, 1);
$output = array();

array_map(function($key, $data) use (&$output){
  $output[$key] = $data;
}, $array2, array_chunk($array, 1, true));
krsort($output);
$output = array_reduce($output, array_merge, array());

var_dump($output);

Output:

array (size=4)
  'c' => int 3
  'b' => int 2
  'a' => int 1
  'd' => int 4

People are also looking for solutions to the problem: php - Jquery Autocomplete to populate tree based sepearated by a string

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.