search

Home  >  Q&A  >  body text

How to sort array based on condition to check maximum 2 digits in laravel sql

In my reply I get

[
    {
        "id": 480,
        "HSN": 4808,
    },
    {
        "id": 575,
        "HSN": 5702,
    },
    {
        "id": 638,
        "HSN": 6301,
    },
    {
        "id": 765,
        "HSN": 7317,
    },
    {
        "id": 6626,
        "HSN": 47071000,
    },
    {
        "id": 6727,
        "HSN": 48081000,
    },
    {
        "id": 6728,
        "HSN": 48084010,
    }
]

But I want my reply to be sorted in a way that checks the HSN (based on the first 2 digits of the HSN) and gives me a result like this

[
    {
        "id": 6626,
        "HSN": 47071000,
    },
    {
        "id": 480,
        "HSN": 4808,
    },
    {
        "id": 6727,
        "HSN": 48081000,
    },
    {
        "id": 6728,
        "HSN": 48084010,
    },
    {
        "id": 575,
        "HSN": 5702,
    },
    {
        "id": 638,
        "HSN": 6301,
    },
    {
        "id": 765,
        "HSN": 7317,
    }
]

I've tried sortBy , the sorting method, but it doesn't seem to work for me, or I'm doing it the wrong way. Help me get it the right way

P粉060112396P粉060112396580 days ago550

reply all(1)I'll reply

  • P粉450079266

    P粉4500792662023-09-09 10:42:03

    First you must read the documentation about usort and strcmp

    $data = [
        [
            "id" => 480,
            "HSN" => 4808,
        ],
        [
            "id"=> 575,
            "HSN"=> 5702,
        ],
        [
            "id"=> 638,
            "HSN"=> 6301,
        ],
        [
            "id"=> 765,
            "HSN"=> 7317,
        ],
        [
            "id"=> 6626,
            "HSN"=> 47071000,
        ],
        [
            "id"=> 6727,
            "HSN"=> 48081000,
        ],
        [
            "id"=> 6728,
            "HSN"=> 48084010,
        ]
    ];
    
    usort($data, function($arr1, $arr2) {
        return strcmp($arr1['HSN'], $arr2['HSN']);
    });
    
    dd($data);

    Explanation about usort and strcmp maybe you have to read the documentation to understand it more deeply.

    reply
    0
  • Cancelreply