LetMeLearn
LetMeLearn

Reputation: 11

I need to sort objects data alphabetically

I have a class Shoes that consists of id, brand, price, size. Also, I already have an sql database from which I get the data for the shoes.

I create a view class Shoes that has 6 columns. 4 aformentioned and 2 extra one with available amount of the shoe left, and one with button "buy".

I would like to have the table in the view_shoes show the shoes in an alphabetical order of the brand. So that I would have

1.Adidas 
2.Geox 
3.Puma 
4.Reebok.

Rather than

1.Reebok 
2.Puma 
3.Adidas 
4. Geox

I couldn't find much information on how to do it. I found functions like usort, asort but I can't figure out how to implement them.

Here is the function for the shoes.

public static function shoes() {
    $query = self::execute("SELECT * FROM shoes", array());
    $data = $query->fetchAll();
    $shoes = [];
    foreach ($data as $row) {
        $shoes[] = new shoe($row['id'], $row["brand"], $row["price"], $row["size"]);
    }
    return $shoes;
}

Upvotes: 1

Views: 55

Answers (3)

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can either modify your SQL query to apply to sort

SELECT * FROM shoes

Replace it with

SELECT * FROM shoes ORDER BY brand ASC

OR you can use sort() function on $shoes if $shoes is an array

sort($shoes);

Upvotes: 1

Sandeep Polamuri
Sandeep Polamuri

Reputation: 609

Write your custom comparator for sorting.

usort($shoes,function ($a,$b){
    return strcmp($a->brand,$b->brand);
    //return strcmp($a['brand'],$b['brand']);
})

Upvotes: 0

Qirel
Qirel

Reputation: 26450

Use ORDER BY in your query, on the brand column.

$query = self::execute("SELECT * 
                         FROM shoes 
                         ORDER BY brand ASC"
                       , array());

Upvotes: 2

Related Questions