# 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 to`10`.
• `b => 2` becomes the second element because it realtes to`7`.
• `a => 1` becomes the third element because it relates to`3`.
• `d => 4` becomes the fourth element because it relates to`1`.
329

#### Solution:

Right, you want to sort with the other array.

``````<?php

\$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);

\$result = array_reverse(\$array, true);
print_r(\$result);

?>
``````
711

#### Solution:

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

1. call`array_multisort()`
2. write the array to be assessed in the first parameter
3. write the`SORT_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

#### 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