简体   繁体   English

使用 $obj->select 对从数据库中提取的数组进行排序

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

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".如果我没看错,它基本上是在说“选择表'the_agent'并抓取状态为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.这些行有一个作为主键的 id 号,所以这就是创建顺序的原因,但是我希望能够按“名称”列对数组进行排序,以便它按字母顺序显示。 Through my research online I have seen and tried many methods such as using JavaScript, using order(), and ORDER BY.通过我的在线研究,我看到并尝试了许多方法,例如使用 JavaScript、使用 order() 和 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. ORDER BY 似乎是完成此任务的最简单和最顺畅的方法,但我无法获得它或任何其他方法来使用 $agent_list 的设置方式。 Is it possible to use ORDER BY with the way it is set up or do I need to use another method?是否可以使用 ORDER BY 的设置方式,还是我需要使用其他方法?

You need to check where $obj is set, it might be an instance of a db query class.您需要检查$obj的设置位置,它可能是数据库查询 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.该 class 的构造函数(或返回分配给$obj的值的 function 的定义)应该提供信息如何指定要包含在数据库查询中的ORDER_BY子句(如果有的话),这是首选方法go。

If that's not an option, sort the php array with a custom sort function:如果这不是一个选项,请使用自定义排序 function 对 php 数组进行排序:

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

Consult usort in the PHP manual for details.有关详细信息,请参阅 PHP 手册中的 usort Code untested.代码未经测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM