0

I have an array of array, I would like to sort it base on the number in each array

[
    ["Plastic and cosmetic surgery",90],
    ["Dermatology surgery",121],
    ["Infertility",134],
    ["Gynecology surgery",191],
    ["Hair transplant",92],
    ["Bariatrics and weight loss surgery",117],
    ["Dentistry",88]
]
3

2 Answers 2

1

There is an amazing and simple default laravel solution for this.

$collection = collect([
        ["Plastic and cosmetic surgery",90],
        ["Dermatology surgery",121],
        ["Infertility",134],
        ["Gynecology surgery",191],
        ["Hair transplant",92],
        ["Bariatrics and weight loss surgery",117],
        ["Dentistry",88]
    ]);

        $sorted = $collection->sortBy(1);

        $data = $sorted->values()->all();
        dd($data);

Output

    array:7 [▼
  0 => array:2 [▼
    0 => "Dentistry"
    1 => 88
  ]
  1 => array:2 [▼
    0 => "Plastic and cosmetic surgery"
    1 => 90
  ]
  2 => array:2 [▼
    0 => "Hair transplant"
    1 => 92
  ]
  3 => array:2 [▼
    0 => "Bariatrics and weight loss surgery"
    1 => 117
  ]
  4 => array:2 [▼
    0 => "Dermatology surgery"
    1 => 121
  ]
  5 => array:2 [▼
    0 => "Infertility"
    1 => 134
  ]
  6 => array:2 [▼
    0 => "Gynecology surgery"
    1 => 191
  ]
]

You can check more functions like this in the documentation. I hope you will enjoy this solution.

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

Comments

0

Try this to sorting value by number.

Input

$array = [
    ["Plastic and cosmetic surgery",90],
    ["Dermatology surgery",121],
    ["Infertility",134],
    ["Gynecology surgery",191],
    ["Hair transplant",92],
    ["Bariatrics and weight loss surgery",117],
    ["Dentistry",88]
];

usort($array, 'sortByNumber');
function sortByNumber($a, $b)
{
    $a = $a[1];
    $b = $b[1];

    if ($a == $b) return 0;
    return ($a < $b) ? -1 : 1;
}

echo "<pre>";
print_r($array);
die;

Output

Array
(
    [0] => Array
        (
            [0] => Dentistry
            [1] => 88
        )

    [1] => Array
        (
            [0] => Plastic and cosmetic surgery
            [1] => 90
        )

    [2] => Array
        (
            [0] => Hair transplant
            [1] => 92
        )

    [3] => Array
        (
            [0] => Bariatrics and weight loss surgery
            [1] => 117
        )

    [4] => Array
        (
            [0] => Dermatology surgery
            [1] => 121
        )

    [5] => Array
        (
            [0] => Infertility
            [1] => 134
        )

    [6] => Array
        (
            [0] => Gynecology surgery
            [1] => 191
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.