Search code examples
phpjoomla

PHP Search filter sort results alphabetically


I'm working on a little webcatalog with a search function. I'm using the software Eshop in Joomla. There is a filter function for manufacturers, but these results aren't displayed alphabetically.

I've looked around for solutions, but I can't get it working. This is the code:

<?php
if (!empty($filterData['manufacturer_ids'])){
    $manufacturerIds = $filterData['manufacturer_ids'];
}
else{
    $manufacturerIds = array();
}

foreach ($manufacturers as $manufacturer){?>
    <li>
        <label class="checkbox">
            <input class="manufacturer" onclick="eshop_ajax_products_filter('manufacturer');" type="checkbox" name="manufacturer_ids[]" value="<?php echo $manufacturer->manufacturer_id; ?>" <?php if (in_array($manufacturer->manufacturer_id, $manufacturerIds)) echo 'checked="checked"'; ?>>
            <?php echo $manufacturer->manufacturer_name; ?><span class="badge badge-info"><?php echo $manufacturer->number_products;?></span>
        </label>
    </li>
<?php }?>

Can anyone help me?

This is the current view


Solution

  • You can use the sort function and I would suggest using the SORT_STRING optional parameter to give you the following.

    $manufacturers = sort($manufacturers, SORT_STRING);
    

    This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

    ...

    SORT_STRING - compare items as strings

    Edit:

    After confirming the data structure, this is an array of objects and requires a custom sorting function. Therefore, you should use usort().

    This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

    So you first define the function that compares the strings for the manufacturer_name property.

    function cmp($a, $b)
    {
        return strcmp($a->manufacturer_name, $b->manufacturer_name);
    }
    
    usort($manufacturers , "cmp");