按特定值对数组进行排序

时间:2021-07-10 10:04:53

Here is the scenario, I have a database and I need data that is different from four tables to display in a list. I was having trouble getting the queries to join in a way that would give the results that I needed in the right order and format so I did a bunch of queries and pushed the results to and array. So now I have this array and it works great so far.

这是场景,我有一个数据库,我需要的数据不同于列表中显示的四个表。我无法以一种能够以正确的顺序和格式提供所需结果的方式来获取查询,因此我做了一堆查询并将结果推送到数组。所以现在我有了这个数组,到目前为止效果很好。

To visualize this I have the data listed in table and I need to sort the table based on the heading.

为了可视化,我有表中列出的数据,我需要根据标题对表进行排序。

What I need to do next is some how sort the array by a specific value.

接下来我需要做的是如何按特定值对数组进行排序。

For example I have the array that contains a value “type” I want to search the array for the specific “types” and then sort the array based on that. So if the “type” column contains items such as “file” , “link” or “quiz” it would sort alphabetically.

例如,我有一个包含值“类型”的数组我想在数组中搜索特定的“类型”,然后根据它对数组进行排序。因此,如果“类型”列包含诸如“文件”,“链接”或“测验”之类的项目,则它将按字母顺序排序。

Is this possible? Or should I be thinking of this in a different way?

这可能吗?或者我应该以不同的方式考虑这个问题?

Can anyone point me in the right direction?

谁能指出我正确的方向?

1 个解决方案

#1


1  

In most cases, you'll probably have better results by letting the database do the work, rather than post-processing it in PHP.

在大多数情况下,通过让数据库完成工作,而不是在PHP中对其进行后处理,您可能会获得更好的结果。

As the other folks are saying, some more specifics and code examples would allow us to provide better help, but based on what you've said:

正如其他人所说,一些更具体的细节和代码示例将允许我们提供更好的帮助,但基于你所说的:

To limit your query results to a specific type, you would add a WHERE clause:

要将查询结果限制为特定类型,可以添加WHERE子句:

SELECT [whatever columns] FROM table_name WHERE type = 'file'

If you want to select multiple types at the same time:

如果要同时选择多个类型:

SELECT [whatever columns] FROM table_name WHERE type IN ('file', 'link', 'quiz')

If you want to order them alphabetically by type:

如果您想按类型按字母顺序排序:

SELECT [whatever columns] FROM table_name WHERE type IN ('file', 'link', 'quiz') ORDER BY type ASC

#1


1  

In most cases, you'll probably have better results by letting the database do the work, rather than post-processing it in PHP.

在大多数情况下,通过让数据库完成工作,而不是在PHP中对其进行后处理,您可能会获得更好的结果。

As the other folks are saying, some more specifics and code examples would allow us to provide better help, but based on what you've said:

正如其他人所说,一些更具体的细节和代码示例将允许我们提供更好的帮助,但基于你所说的:

To limit your query results to a specific type, you would add a WHERE clause:

要将查询结果限制为特定类型,可以添加WHERE子句:

SELECT [whatever columns] FROM table_name WHERE type = 'file'

If you want to select multiple types at the same time:

如果要同时选择多个类型:

SELECT [whatever columns] FROM table_name WHERE type IN ('file', 'link', 'quiz')

If you want to order them alphabetically by type:

如果您想按类型按字母顺序排序:

SELECT [whatever columns] FROM table_name WHERE type IN ('file', 'link', 'quiz') ORDER BY type ASC