Home  >  Article  >  Backend Development  >  Detailed explanation of how to use PHP custom function to implement two-dimensional array sorting function

Detailed explanation of how to use PHP custom function to implement two-dimensional array sorting function

墨辰丷
墨辰丷Original
2018-06-01 16:56:411698browse

This article mainly introduces the PHP custom function to implement the two-dimensional array sorting function, involving PHP's array judgment, traversal, conversion, sorting and other related operation skills. Friends in need can refer to it

/**作用: 二维数组排序函数,支持多键名排序
 * 返回: 排序好的数组
 * 使用: array_msort(数组,需要排序的键名,排序方式);
 * 例子: array_msort($cflist,"chapter_orderid","SORT_ASC");
 *    array_msort($arr,"name","SORT_ASC","type","SORT_DESC","size","SORT_ASC","SORT_STRING");
 */
function array_msort($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR") {
  if(!is_array($ArrayData)) {
    return $ArrayData;
  }
  // 获取参数数量.
  $ArgCount = func_num_args();
  // 排序,并放置到SortRule数组
  for($i = 1;$i < $ArgCount;$i ++) {
    $Arg = func_get_arg($i);
    if(!eregi("SORT",$Arg)) {
      $KeyNameList[] = $Arg;
      $SortRule[] = &#39;$&#39;.$Arg;
    }
    else {
      $SortRule[] = $Arg;
    }
  }
  // Get the values according to the keys and put them to array.
  foreach($ArrayData AS $Key => $Info) {
    foreach($KeyNameList AS $KeyName) {
      ${$KeyName}[$Key] = $Info[$KeyName];
    }
  }
  // Create the eval string and eval it.
  $EvalString = &#39;array_multisort(&#39;.join(",",$SortRule).&#39;,$ArrayData);&#39;;
  eval($EvalString);
  return $ArrayData;
}

Summary: The above is the entire content of this article. I hope it will be helpful to everyone's study.

Related recommendations:

How to implement simple bubble sorting in PHP

How to remove slashes in PHP when submitting a form

Detailed explanation of PHP form submission and form data processing

The above is the detailed content of Detailed explanation of how to use PHP custom function to implement two-dimensional array sorting function. For more information, please follow other related articles on the PHP Chinese website!

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