PHP: multi-dimensional array with multiple sorts

I have an array with 4 values ​​each

$array[0] = array('amount' => '98.60', 'typeA' => '98.52', 'typeB' => '58.52', 'typeC' => '90.2'); $array[1] = array('amount' => '55.80', 'typeA' => '25.36', 'typeB' => '36.54', 'typeC' => '36.99'); $array[2] = array('amount' => '42.68', 'typeA' => '64.26', 'typeB' => '65.87', 'typeC' => '99.24'); $array[3] = array('amount' => '812.3', 'typeA' => '36.27', 'typeB' => '23.25', 'typeC' => '94.35'); 

I need to arrange the array according to the highest value of each key with the sequence:

  • Typea
  • Typeb
  • typeC

therefore, in the end, I will get to see how much will be up.

Hope you can help here, thanks!

+4
source share
2 answers

$ data = array (array ('amount' => '98 .60 ',' typeA '=> '98 .52', 'typeB' => '58 .52 ',' typeC '=> '90 .2'), array ('quantity' = > '55 .80 ',' typeA '=> '25 .36', 'typeB' => '36 .54 ',' typeC '=> '36 .99'), array ('amount' => '42 .68 ',' typeA '=>' 64.26 ',' typeB '=> '65 .87', 'typeC' => '99 .24 '), array (' amount '=>' 812.3 ',' typeA '=> '36 .27', 'typeB' => '23 .25 ' , 'typeC' => '94 .35 '));

// Get a list of columns

foreach ($ data as $ key => $ row) {

 $volume[$key] = $row['typeA']; $edition[$key] = $row['typeB']; $edition1[$key] = $row['typeC']; 

}

array_multisort ($ volume, SORT_DESC, $ edition, SORT_DESC, $ edition1, SORT_DESC, $ data);

echo ''; print_r ($ data);

+2
source

array_multisort () can be used to sort multiple arrays at once or a multidimensional array in one or more dimensions.

http://php.net/manual/en/function.array-multisort.php

 <?php $data[] = array('volume' => 67, 'edition' => 2); $data[] = array('volume' => 86, 'edition' => 1); $data[] = array('volume' => 85, 'edition' => 6); $data[] = array('volume' => 98, 'edition' => 2); $data[] = array('volume' => 86, 'edition' => 6); $data[] = array('volume' => 67, 'edition' => 7); // Pass the array, followed by the column names and sort flags $sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC); ?> 

Here is another great example of its use:

PHP sort array by two field values

+1
source

All Articles