简体   繁体   English

对二维数组进行排序

[英]Sorting a Two-Dimensional Array

I am new to PHP. 我是PHP的新手。 I have a PHP array that is two dimensional. 我有一个二维的PHP数组。 The "inner" array has a value that I want to sort on. “内部”数组有一个我想要排序的值。

For example: 例如:

$myarray[1]['mycount']=12
$myarray[2]['mycount']=13
$myarray[3]['mycount']=9

I want to sort the "inner" array in descending order. 我想按降序排序“内部”数组。

So the results for the following will be 13, 12, 9 因此,以下结果将是13,12,9

foreach ($myarray as $myarr){
  print $myarr['mycount']
}

thanks in advance. 提前致谢。

You can use usort(); 你可以使用usort(); to sort by a user-defined comparison. 按用户定义的比较排序。

// Our own custom comparison function
function fixem($a, $b){
  if ($a["mycount"] == $b["mycount"]) { return 0; }
  return ($a["mycount"] < $b["mycount"]) ? -1 : 1;
}

// Our Data
$myarray[0]['mycount']=12
$myarray[1]['mycount']=13
$myarray[2]['mycount']=9

// Our Call to Sort the Data
usort($myArray, "fixem");

// Show new order
print "<pre>";
print_r($myArray);
print "</pre>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM