user3710676
user3710676

Reputation: 35

mysql php random results sort by name

I need to order by the name from the random results. My sql command:

SELECT * FROM oc_manufacturer ORDER BY RAND() ASC LIMIT 0,50

And it returns thhis array:

   [0] => Array
        (
            [manufacturer_id] => 16
            [name] => Azzaro
        )

    [1] => Array
        (
            [manufacturer_id] => 71
            [name] => Sony
        )

    [2] => Array
        (
            [manufacturer_id] => 104
            [name] => Casio
        )

    [3] => Array
        (
            [manufacturer_id] => 30
            [name] => Jeepers Peepers
        )

But i want to return first Azzaro, then Casio, then Jeepers Peepers, and Sony. I need to sort results by name from RAMDOM results. I tried sort arrays and some mysql commands but it is not worked.

Upvotes: 2

Views: 85

Answers (1)

Eloims
Eloims

Reputation: 5224

You can either

make a subquery (see Strawberry comment)

SELECT * FROM (SELECT * FROM oc_manufacturer ORDER BY RAND() LIMIT 50)x ORDER BY name;

sort the array in PHP

$array = ....; // make query
usort($array, function($item1, item2) {
    return strcmp($item1['name'], $item2['name']);
});

Upvotes: 2

Related Questions