8

I have array like below

Array
(
    [0] => Array
        (
            [0] => 1280
            [id] => 1280
        )

    [1] => Array
        (
            [0] => 2261
            [id] => 2261
        )

    [2] => Array
        (
            [0] => 1280
            [id] => 1280
        )
)

In php, How do I sort from low to high based on the value of "id" ?

1

2 Answers 2

14

use usort(), like:

function sortById($x, $y) {
    return $x['id'] - $y['id'];
}

usort($array, 'sortById');
echo "<pre>"; print_r($array);
1
  • Note that while this is generally true, it is not for float values below 1. You should take the sign of the difference before returning the comparison. Commented Apr 18, 2020 at 15:41
0

use array_multisort() like below:

<?php
$multiArray = Array(
    Array("id" => 120, "name" => "Defg"),
    Array("id" => 62, "name" => "Abcd"),
    Array("id" => 99, "name" => "Bcde"),
    Array("id" => 2, "name" => "Cdef"));
$tmp = Array();
foreach($multiArray as &$ma)
    $tmp[] = &$ma["id"];
array_multisort($tmp, $multiArray);
foreach($multiArray as &$ma)
    echo $ma["id"]."<br/>";

/* Outputs
    2
62
99
120
*/
?> 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.