Sorting an array pulled from database using $obj->select

ProfessionallyInept :

I have inherited a project from another developer that has a bunch of dropdown menus that pull information from the database. The way this is set up is as follows:

$agent_list = $obj->select(TABLEPRIFIX.'agent', '*', ['status' =>1 ]);

If I am reading this correctly it is basically saying "select table 'the_agent' and grab everything with a status of 1". That part works fine however the dropdown menu that is as follows:

<div class="form-group">
    <label>Agent</label>
    <select name="agent_id" id="" class="form-control" required>
        <option value="">Select</option>
        <?php
        foreach ($agent_list as $agent) 
        {
            ?>
            <option value="<?php echo $agent['id']; ?>" <?php echo ($agent['id'] == $agent[0]['agency_id']) ? 'selected': '' ?> ><?php echo $agent['name']; ?></option>

Will display all the names in non-alphabetical order. The rows have an id number that is the primary key so that is what creates the order however I would like to be able to sort the array by the "name" column so it will display as alphabetical order. Through my research online I have seen and tried many methods such as using JavaScript, using order(), and ORDER BY. The ORDER BY seems to be the easiest and smoothest way of to accomplish this but I am not able to get it or any other method to work with the way $agent_list is set up. Is it possible to use ORDER BY with the way it is set up or do I need to use another method?

collapsar :

You need to check where $obj is set, it might be an instance of a db query class. The constructor of that class (or the definition of the function returning the value assigned to $obj) should provide the info how you can specify an ORDER_BY clause to be included in the DB query (if at all), which is the preferred way to go.

If that's not an option, sort the php array with a custom sort function:

 usort($agent_list, function ($a, $b) { return strcmp($a['name'], $b['name']); });

Consult usort in the PHP manual for details. Code untested.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397954&siteId=1