Welcome Guest, Not a member yet? Register   Sign In
Custom Sort Query Syntax
#1

Hey guys,
I'm hoping you can help me figure out the correct syntax for a query.
PHP Code:
$main_cat $this->db->from('categories')
 
    ->where("deleted"0)
 
    ->where("hide_from_grid"0)
 
    ->where("parent_id"null)
 
    ->get()->result();

This code returns an array of 15 objects (I am listing just two of the 15 below):

Array 
PHP Code:
(
    [0] => stdClass Object
        
(
            [id] => 4
            
[ecommerce_category_id] => 100
            
[last_modified] => 2022-04-12 13:35:18
            
[deleted] => 0
            
[hide_from_grid] => 0
            
[parent_id] => 
            [name] => Beverages
            
[image_id] => 
            [color] => 
            [system_category] => 0
            
[exclude_from_e_commerce] => 0
            
[category_info_popup] => 
        )

    [1] => stdClass Object
        
(
            [id] => 8
            
[ecommerce_category_id] => 106
            
[last_modified] => 2022-04-12 13:48:57
            
[deleted] => 0
            
[hide_from_grid] => 0
            
[parent_id] => 
            [name] => Condiments
            
[image_id] => 
            [color] => 
            [system_category] => 0
            
[exclude_from_e_commerce] => 0
            
[category_info_popup] => 
        

By looping through the array, I am extracting the [name] for each member of the array:
PHP Code:
foreach ($main_cat as $key_main_cat => $values_main_cat)
 {
 
    echo $values_main_cat->name;
 
    echo "<br>"
}
Which produces the following result:
Beverages
Condiments
Canned Fruits, Vegetables, & Meats
Household
Soups, Broth, & Gravies
Pastas, Rice & Grains
Breakfast
Kitchen
Paper Products
Beans & Chili
Baking & Cooking
Baby Products
Health & Beauty
C-Store Supplies
Snacks

I would like to sort this list in a custom order. I can think of two ways of doing this, but can't figure out the syntax for either method.

Method 1: Use Order_By condition in the query

I tried:

PHP Code:
->order_by("id""8,4,11,35,27,44,72,50,19,33,51,52,80,12,30"

but it didn't work. What would be the correct syntax?

Method 2: Sort the $main_cat array after the data has been populated

No idea how to do this.... probably simpler than method 1, but don't know how to sort the array using the custom order.

I appreciate your time and assistance!!
Reply


Messages In This Thread
Custom Sort Query Syntax - by imranp - 06-15-2022, 01:08 PM



Theme © iAndrew 2016 - Forum software by © MyBB