Home > Backend Development > PHP Tutorial > Two examples of php two-dimensional array sorting

Two examples of php two-dimensional array sorting

WBOY
Release: 2016-07-25 08:56:34
Original
913 people have browsed it
This article introduces two examples of two-dimensional array sorting in PHP, both of which are relatively simple. It is a good reference for friends who are learning PHP array sorting.

Share a piece of code to implement sorting of two-dimensional arrays in php. Code:

<?php
/**
* 二维数组排序
* by bbs.it-home.org
*/
 $good = array();
 
 for($i = 0; $i<7 ; $i++ ){
     
     $good[$i]['price']  = rand(1,10000);
    $good[$i]['hot']    = rand(1,100);
     $good[$i]['follow'] = rand(1,1000);    
 
 }
 
 echo '<pre class="brush:php;toolbar:false">';
 
print_r($good);

echo '
Copy after login
'; $hot=array(); $follow=array(); foreach($good as $k=>$v){ $hot[$k] = $v['hot']; $follow[$k] = $v['follow']; } //Sort two-dimensional array //Method 1, first sort in descending order by hot field, and then in descending order by follow array_multisort($hot,SORT_DESC,$follow,SORT_DESC,$good); echo '
';
print_r($good);
echo '
Copy after login
'; //Method Two functionxx($a, $b) { if ($a['price'] == $b['price']) { return ($a['hot'] < $b['hot']) ? 1 : -1; ; } return ($a['price'] < $b['price']) ? 1 : -1; } $a = array( 0=>array('price'=>123,'hot'=>34543), 1=>array('price'=>434,'hot'=>234), 2=>array('price'=>42,'hot'=>2232), 3=>array('price'=>42,'hot'=>235432), 4=>array('price'=>33443,'hot'=>12), 4=>array('price'=>434,'hot'=>1211), ); usort($a, 'xx'); echo '
';
print_r($a);
echo '
Copy after login
';

>>> For more information, please view the complete list of php array sorting methods



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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template