5

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 of:

  1. typeA
  2. typeB
  3. typeC

so in the end I will get to see which is the amount that comes up top.

Hope some help can be given here, thanks!

0

2 Answers 2

3

$data = array(array('amount' => '98.60', 'typeA' => '98.52', 'typeB' => '58.52', 'typeC' => '90.2'), array('amount' => '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'));

// Obtain 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);

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

Comments

1

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by 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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.