-3

I want to sort a multidimensional array in numerical order bu second value of each item.

This is array:

$vulc = array(
        array('s',3),
        array('s',5),
        array('s',2)
    );

and i want this output:

$vulc = array(
        array('s',5),
        array('s',3),           
        array('s',2)
    );

I'm tried this:

foreach ($vulc as $key => $row) {
    $distance[$key] = $row[2];
}

array_multisort($distance, SORT_ASC, $vulc);

but doesn't work :( please help me and not suggest to see other answer... usually other answer are too difficult :(

Borja
  • 3,359
  • 7
  • 33
  • 66
  • 1
    I'm gonna ignore your "other answer" remark and link this, since it really can't get any less difficult than this: http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value – Loek Jun 09 '16 at 13:11
  • 4
    I already closed your last question and in the duplicate there are multiple solutions how to solve it: http://stackoverflow.com/q/17364127/3933332 I can't make the answer more obvious. – Rizier123 Jun 09 '16 at 13:14
  • @Rizier123 i know and i see your linked question... but for me is too difficult understand the accepted answer in there question: is difficult beacause is big, i'm not able with php e because i'm italian and don't understand english – Borja Jun 09 '16 at 13:17

3 Answers3

2

Use rsort()

$vulc = array(
        array('s',3),
        array('s',5),
        array('s',2)
    );
rsort($vulc);
echo "<pre>";
print_r($vulc);

Output

Array
(
    [0] => Array
        (
            [0] => s
            [1] => 5
        )

    [1] => Array
        (
            [0] => s
            [1] => 3
        )

    [2] => Array
        (
            [0] => s
            [1] => 2
        )

)
RJParikh
  • 4,096
  • 1
  • 19
  • 36
1

Use the usort function and Try:

function sortByOrder($a, $b) {
    return $b[1] - $a[1]; // $b[1] - $a[1] because it need to be descending order
}

usort($vulc, 'sortByOrder');

Output:

Array
(
    [0] => Array
        (
            [0] => s
            [1] => 5
        )

    [1] => Array
        (
            [0] => s
            [1] => 3
        )

    [2] => Array
        (
            [0] => s
            [1] => 2
        )

)
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
0

You can sort, and add 's' to sorted array:

<?php
$vulc = array(
    array('s',3),
    array('s',5),
    array('s',2)
);

foreach ($vulc as $key => $row) {
    $distance[] = $row[1];
}

array_multisort($distance, SORT_ASC, $vulc);

foreach ($distance as $row) {
    $vulcOut[] = ['s', $row];
}

// $vulcOut = array(
//     array('s',5),
//     array('s',3),
//     array('s',2)
// );
Ivan
  • 2,463
  • 1
  • 20
  • 28