Home  >  Article  >  Backend Development  >  Specific implementation of PHP two-dimensional array sorting according to a certain field_PHP tutorial

Specific implementation of PHP two-dimensional array sorting according to a certain field_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:29:03843browse

The function to be implemented recorded in this article is similar to ORDER BY in MySQL. Such a requirement was encountered in the previous project.

Requirement: Get 4 pieces of data from two different tables, then integrate (array_merge) into an array, and then sort the first 4 pieces in descending order according to the creation time of the data.

When encountering this requirement, ORDER BY cannot solve the problem. So I looked through the PHP manual and found the following method and made this note. < ;?php
/**
* Sort the two-dimensional array according to a certain field
* Function: Sort by the user’s age in reverse order

* @author ruxing.li */ header('Content-Type: text/html;Charset=utf-8'); $arrUsers = array( array(
'id' => 1,
'name' => '张三',
'age' => 25,
),
array(
'id ' => 2,
'name' => '李思',
'age' => 23,
),
array(
'id' => 3,
'name' => '王五',
'age' => 40,
),
array(
'id' => 4,
>'name' => 'Zhao Liu',
'age' => 31,
),
array(
'id' => 5,
'name' => '黄七',
'age' => 20,
),
);


$sort = array(
'direction' = > 'SORT_DESC', //Sort order flag SORT_DESC descending order; SORT_ASC ascending order
'field' => 'age', //Sort field
);
$arrSort = array();
foreach($arrUsers AS $uniqid => $row){
foreach($row AS $key=>$value){
$arrSort[$key][$uniqid] = $value;
}
}
if($sort['direction']){
array_multisort($arrSort[$sort['field']], constant($sort['direction']), $ arrUsers);
}

var_dump($arrUsers);

/*
Output result:

array (size=5)
0 = >
array (size=3)
'id' => int 5
'name' => string '黄七' (length=6)
'age' => int 20
1 =>
array (size=3)
'id' => int 2
'name' => string '李思' (length=6)
'age' => int 23
2 =>
array (size=3)
'id' => int 1
'name' => string '张三' (length=6)
'age' => int 25
3 =>
array (size=3)
'id' => int 4
'name' = > string '赵六' (length=6)
'age' => int 31
4 =>
array (size=3)
'id' => int 3
'name' => string '王五' (length=6)
'age' => int 40

*/





http://www.bkjia.com/PHPjc/779572.html

www.bkjia.com

true

http: //www.bkjia.com/PHPjc/779572.html

TechArticle

The function to be implemented recorded in this article is similar to ORDER BY in MySQL. I encountered this in the previous project A demand. Requirement: Get 4 pieces of data from two different tables, and then...
Statement:
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