Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - sort array by array key [duplicate]

I have this array in PHP:

In PHP APIs I have this array and want to sort ot by custom_price, but not getting how to acheive so ..

Array
(
    [0] => Array
        (
            [id] => 1204
            [custom_price] => 33.1500
        )


    [1] => Array
        (
            [id] => 1199
            [custom_price] => 16.83
        )

    [2] => Array
        (
            [id] => 1176
            [custom_price] => 16.83
        )

    [3] => Array
        (
            [id] => 1173
            [custom_price] => 11.73
        )

    [4] => Array
        (
            [id] => 1170
            [custom_price] => 22.5
        )
)

How i can sort from .. high to low & low to high .. by custom_price

like image 931
Narendra.vyas Avatar asked Jun 01 '18 05:06

Narendra.vyas


3 Answers

Using usort:

high to low

usort($input, function ($a, $b) {return $a['custom_price'] < $b['custom_price'];});
print_r( $input );

low to high

usort($input, function ($a, $b) {return $a['custom_price'] > $b['custom_price'];});
print_r( $input );

http://php.net/manual/en/function.usort.php

like image 196
Karlo Kokkak Avatar answered Sep 29 '22 07:09

Karlo Kokkak


This solution might help you.

function sortByOrder($a, $b) {
    return $a['custom_price'] - $b['custom_price'];
}

usort($myArray, 'sortByOrder');

Or

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($your_array,"custom_price");

here is reference link

like image 37
Jalpesh Patel Avatar answered Sep 29 '22 06:09

Jalpesh Patel


use array_multisort() with SORT_DESC and SORT_ASC

<?php

    $MYarray=
    array(
    0 => array(
           "id"=> 1204,
           "custom_price"=> 33.1500
        ),
    1 =>  array(
           "id"=> 1199,
           "custom_price"=> 16.83
        ),
    2 => array(
           "id"=> 1176,
           "custom_price"=> 316.83
        ));


    $custom_price = array();
    foreach ($MYarray as $key => $row)
    {
        $custom_price[$key] = $row['custom_price'];
    }

    array_multisort($custom_price, SORT_DESC, $MYarray);


    var_dump($MYarray);
    ?>
like image 35
Saurabh Mistry Avatar answered Sep 29 '22 06:09

Saurabh Mistry