2013-10-18 125 views
0

嗨如何排序一個多維數組,取決於3個值,ps_kind,ps_date,ps_premium。 我會感謝任何答案或片段。由三個值排序多維數組

Array 
(
    [0] => Array 
     (
      [ps_date] => 2013-08-05 20:56:33 
      [ps_kind] => Gold 
      [ps_premium] = > 1 
     ) 
    [1] => Array 
     (
      [ps_date] => 2013-08-05 20:46:33 
      [ps_kind] => Gold 
      [ps_premium] = > 0 
     ) 
    [2] => Array 
     (
      [ps_date] => 2013-08-05 20:16:33 
      [ps_kind] => Silver 
      [ps_premium] = > 0 
     ) 

    [3] => Array 
     (
      [ps_date] => 2013-08-05 20:06:33 
      [ps_kind] => Bronze 
      [ps_premium] = > 0 
     ) 
) 

我用這個代碼努力,但他不工作正確

function cmp($a, $b) 
     { 
      $pos = array (
       'Gold'  => 1, 
       'Silver'  => 2, 
       'Bronze'  => 3, 
      ); 
      list ($a1, $c1) = explode('', $a['ps_kind']); 
      list ($a2, $c2) = explode('', $b['ps_kind']); 
      $catcmp = strcmp(trim($c1), trim($c2)); 
      if ($catcmp==0) 
       return $pos[trim($a1)] - $pos[trim($a2)]; 
      else return $catcmp; 
     } 



     $result = $this -> db ->query($query); 



     foreach ($result as $element) { 

      $array[] = $element; 
     } 

     usort($array,'cmp'); 

     $index = 0; 

     foreach ($array as $single) { 

      $count = $index + 1; 


      if($array[$index]['ps_date'] < $array[$count]['ps_date'] && $array[$index]['ps_kind'] == $array[$count]['ps_kind']) { 

       $prev = $array[$index]; 

       $next = $array[$count]; 

       $array[$index] = $next; 

       $array[$count] = $prev; 

      } 

      $index++; 

     } 
+4

這不是一個網站,您可以免費索取代碼!向我們展示您嘗試過的方式,我們將幫助您。 – ComFreek

+0

我沒有打算要求代碼bcz我寫了「或片段」,所以我認爲有人可以寫線索或somthing – wrcode

+0

我想你可以使用[''usort'](http://php.net/manual /en/function.usort.php)與一個自定義函數。 – Sumurai8

回答

0

如果您使用usort,則可以使用用戶定義的函數對數組進行排序。此函數必須返回-1,0或1.以下示例代碼將首先測試ps_kind,如果它們相同,則將測試ps_premium。這將首先與'青銅'分類。

function test($a, $b) { 
    $pos = Array('Gold' => 1, 'Silver' => 2, 'Bronze' => 3); 
    if($pos[$a['ps_kind']] < $pos[$b['ps_kind']]) { 
    return 1; 
    } else if($a['ps_kind'] == $b['ps_kind']) { 
    if($a['ps_premium'] < $b['ps_premium']) { 
     return 1; 
    } else if($a['ps_premium'] == $b['ps_premium']) { 
     return 0; 
    } else { 
     return -1; 
    } 
    } else { 
    return -1; 
    } 
} 

$x = Array(Array 
     (
      ps_date => "2013-08-05 20:56:33", 
      ps_kind => "Gold", 
      ps_premium => 1 
     ), Array 
     (
      ps_date => "2013-08-05 20:06:33", 
      ps_kind => "Bronze", 
      ps_premium => 0 
     ), Array 
     (
      ps_date => "2013-08-05 20:46:33", 
      ps_kind => "Gold", 
      ps_premium => 0 
     ), Array 
     (
      ps_date => "2013-08-05 20:16:33", 
      ps_kind => "Silver", 
      ps_premium => 0 
     ) 
); 

usort($x, "test"); 
var_dump($x); 
0

如何做某事。像這樣:http://php.net/manual/en/function.usort.php

和替換$a$a['ps_kind'](同爲$ B)和$a['ps_kind'] == $b['ps_kind']你ps_date再次添加同樣的功能,所以如果ps_kind是相同的排序ps_date(相同於ps_date => ps_premium)

如果您在此處嘗試=>註釋之後對此有疑問:)