PHP Implementation Array Sort Operation Example According to a Cell Field

  • 2021-10-25 06:17:46
  • OfStack

In this paper, the example tells us that PHP implements the sorting operation of arrays according to a certain unit field. Share it for your reference, as follows:

As in the question, give an PHP array with the following array structure:


$arr = array(
  array(
    'name'=>'sadas',
    'norder'=>1
  ),
  array(
    'name'=>'sadas',
    'norder'=>11
  ),
  array(
    'name'=>'sadas',
    'norder'=>123
  ),
  array(
    'name'=>'sadas',
    'norder'=>11
  )
);

Need is to rearrange the order of the $arr array in order of norder from large to small.

You can use the array_multisort Function to help sort:


function p($arr){
  echo "<pre>";
  print_r($arr);
  echo "</pre>";
}
$arr = array(
  array(
    'name'=>'sadas',
    'norder'=>1
  ),
  array(
    'name'=>'sadas',
    'norder'=>11
  ),
  array(
    'name'=>'sadas',
    'norder'=>123
  ),
  array(
    'name'=>'sadas',
    'norder'=>11
  )
);
$flag = array();
foreach($arr as $v){
  $flag[] = $v['norder'];
}
array_multisort($flag, SORT_DESC, $arr);
p($arr);

Run results:

Array
(
[0] = > Array
(
[name] = > sadas
[norder] = > 123
)
[1] = > Array
(
[name] = > sadas
[norder] = > 11
)
[2] = > Array
(
[name] = > sadas
[norder] = > 11
)
[3] = > Array
(
[name] = > sadas
[norder] = > 1
)
)

PS: Here we recommend another demonstration tool about sorting for your reference:

Online animation demonstrates insert/select/bubble/merge/hill/quick sort algorithm process tool:
http://tools.ofstack.com/aideddesign/paixu_ys

For more readers interested in PHP related contents, please check the special topics of this site: Summary of php Sorting Algorithm, Tutorial of PHP Data Structure and Algorithm, Summary of php Programming Algorithm, Summary of php String (string) Usage, Encyclopedia of PHP Array (Array) Operation Skills, Summary of PHP Common Traversal Algorithms and Skills and Summary of PHP Mathematical Operation Skills

I hope this article is helpful to everyone's PHP programming.


Related articles: