本文介绍了使用多个条件对php中的关联数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下数组

    $details = array( 
 array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
 array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n'),
 array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
 array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
 array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n')
    );

这里我想用 head 和 membkey 进行排序.同一个 membkey 元素的顶部元素应该有 'head=y' 并回显为,

Here I would like to sort with head and membkey. Top element of same membkey element should have 'head=y' and echoed as,

    $details = array( 
 array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
 array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n'),
 array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
 array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
 array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n')
    );

我试过如下

    function orderbymemberKey( $a, $b ){
    if ( $a[membkey] == $b[membkey] )
        return 0;
    return($a[membkey] < $b[membkey] )? -1 :1;
 }
 usort( $details, orderbymemberKey );
and it successfully order by membkey.

请提出任何建议.

推荐答案

您已经成功了一半(尽管您根据您的示例对 membkey 进行了倒序排序):

You're half way there (though you were sorting backwards for membkey based on your example):

function order_by_member_key($a, $b)
{
  if ($a['membkey'] == $b['membkey'])
  {
    // membkey is the same, sort by head
    if ($a['head'] == $b['head']) return 0;
    return $a['head'] == 'y' ? -1 : 1;
  }

  // sort the higher membkey first:
  return $a['membkey'] < $b['membkey'] ? 1 : -1;
}
usort($details, "order_by_member_key");

这篇关于使用多个条件对php中的关联数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 22:58