0

I am trying to sort multidimensional array by values total in php.

[ c => [1=>22, 2=> 14, 3=> 55], a => [7=> 33, 2=> 19, 51=> 43, 14=> 27], ... ]

since values total of a subarray are higher than in c, it should be first in this example. I would appreciate very much help regarding this problem.

6
  • 2
    uasort($arr, function($a, $b) { return array_sum($b) - array_sum($a);}); Commented Nov 9, 2019 at 20:17
  • Perhaps this page can be helpful stackoverflow.com/questions/33720295/… Commented Nov 9, 2019 at 20:17
  • @splash58 i tried but it is not working, even the array keys (a,c) are not kept. Commented Nov 9, 2019 at 20:22
  • I've update the comment, try now Commented Nov 9, 2019 at 20:22
  • @Thefourthbird this function does sort properly, but array keys are not kept. Commented Nov 9, 2019 at 20:26

2 Answers 2

0

You can use array_multisort with array_map

array_multisort(array_map(function($v){return array_sum($v);},$a), SORT_DESC, $a);

First argument with array_map is the sum of the all sub-array. You can change the order of the result array by modifying the 2nd argument SORT_ASC, SORT_DESC

Working example : https://3v4l.org/4fpXh

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

Comments

0

As @splash58 comment (just to make formal answer):

Use uasort() and array_sum as:

uasort($arr, function($a, $b) { return array_sum($b) - array_sum($a);});

Live example: 3v4l

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.