How to use the php array_multisort function to perform complex sorting of database results

高洛峰
Release: 2023-03-04 16:54:01
Original
1147 people have browsed it

First let’s talk about the requirements: There are 4 fields in the database, namely id, volume, edition, and name. It is required to sort the query results from large to small according to volume+edition.
The array_multisort function will be discussed below
array_multisort() can be used to sort multiple arrays at one time, or to sort multi-dimensional arrays according to a certain dimension or multiple dimensions.

Associated (string) key names remain unchanged, but numeric key names will be re-indexed.

Sort order flag:
SORT_ASC – Sort in ascending order
SORT_DESC – Sort in descending order

Sort type flag:
SORT_REGULAR – Compare items in the usual way
SORT_NUMERIC - Compare items based on numeric values
SORT_STRING - Compare items based on strings

You cannot specify two similar sorting flags after each array. The sort flags specified after each array are valid only for that array – before that the default values SORT_ASC and SORT_REGULAR were used.

The input array is treated as a table column and sorted by row - this is similar to the functionality of SQL's ORDER BY clause. The first array is the main array to be sorted. If the rows (values) in the array are compared to be the same, they are sorted according to the size of the corresponding value in the next input array, and so on.

The parameter structure of this function is somewhat unusual, but very flexible. The first parameter must be an array. Each of the following arguments can be an array or a sort flag listed below.

So we now have such a set of data

// 这是一组从数据库查询出来的结果 $data[] = array('volume' => 67, 'edition' => 2); $data[] = array('volume' => 86, 'edition' => 1); $data[] = array('volume' => 85, 'edition' => 6); $data[] = array('volume' => 98, 'edition' => 2); $data[] = array('volume' => 86, 'edition' => 6); $data[] = array('volume' => 67, 'edition' => 7); //我们需要先做出一个volume+edition的数组来 foreach($data as $val){ $arr[] = $val['volume'] + $val['edition']; } // 将$arr根据降序排列 // 把 $data 作为最后一个参数,以通用键排序 array_multisort($arr, SORT_DESC, $data);
Copy after login

This achieves the functions we need

More related articles on how to use the php array_multisort function to perform complex sorting of database results Please pay attention to PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!