PHP基于离线或在线排序

时间:2010-12-16 21:38:27

标签: php arrays sorting multidimensional-array

我有一个多维数组,如下所示:

[Jack] => Array
    (
        [GCF] => Array
            (
                [Name] => Jack
                [retrieved] => cache
            )
        [PF] => Array
            (
                [lastSeen] => Fri, 03 Dec 2010 23:48:14 GMT
                [online] => 0
            )
     )
... More users here in the same format

由此我想对数组进行排序,以便首先显示在线用户,但我希望PHP尽可能不修改数组或其任何键。

任何人对如何做到这一点都有任何想法?

感谢。

2 个答案:

答案 0 :(得分:1)

 function array_sort($array, $on, $order='SORT_DESC') 
    { 
      $new_array = array(); 
      $sortable_array = array(); 

      if (count($array) > 0) { 
          foreach ($array as $k => $v) { 
              if (is_array($v)) { 
                  foreach ($v as $k2 => $v2) { 
                      if ($k2 == $on) { 
                          $sortable_array[$k] = $v2; 
                      } 
                  } 
              } else { 
                  $sortable_array[$k] = $v; 
              } 
          } 

          switch($order) 
          { 
              case 'SORT_ASC':    
                  echo "ASC"; 
                  asort($sortable_array); 
              break; 
              case 'SORT_DESC': 
                  echo "DESC"; 
                  arsort($sortable_array); 
              break; 
          } 

          foreach($sortable_array as $k => $v) { 
              $new_array[] = $array[$k]; 
          } 
      } 
      return $new_array; 
    } 

答案 1 :(得分:0)

$users = <input array>

$online = $offline = array();
foreach ($users as $name => $data) {
  if ($data['PF']['online']) {
    $online[$name] = $data;
  } else {
    $offline[$name] = $data;
  }
}

$sorted = array_merge($online, $offline);