2014-01-23 65 views
2

我有一個數組,我需要排序,我會發佈一個例子,以便更好地理解。 這是我排序的數組:PHP - 一個數組的非標準排序

[0] => Array 
    (
     [title] => This is some title 
     [catid] => 1 
    )  
[1] => Array 
    (
     [title] => This is some title 
     [catid] => 1 
    ) 
[2] => Array 
    (
     [title] => This is some title 
     [catid] => 2 
    )  
[3] => Array 
    (
     [title] => This is some title 
     [catid] => 2 
    ) 

我需要重新梳理這樣的:

[0] => Array 
    (
     [title] => This is some title 
     [catid] => 1 
    )  
[1] => Array 
    (
     [title] => This is some title 
     [catid] => 2 
    ) 
[2] => Array 
    (
     [title] => This is some title 
     [catid] => 1 
    )  
[3] => Array 
    (
     [title] => This is some title 
     [catid] => 2 
    ) 

我將有更多的兩大類,我需要選擇每個類別的一個項目,所以如果我有3類,我在這種情況下CATID進行排序是這樣的:

CATID: 1,2,3,1,2,3

謝謝

+1

可能它曾經是1,2,3,1,3? –

+1

...或1,2,3,1,1,1? – 2014-01-23 00:57:20

+1

更準確地說,如果沒有像1 2 1,2 2 3 3這樣的1,2,3的偶數陣容,會發生什麼 –

回答

4

這裏是我的看法:

/** just generating some data, not part of script **/ 
$originalArray = array(); 
$title = range('a','z'); 
for ($x=0;$x<20;$x++) { 
    shuffle($title); 
    $originalArray[] = array(
    'title' => implode(array_slice($title,0,rand(4,9))), 
    'catid' => rand(1,3) 
); 
} 
/** end generating data **/ 


$tempArray = array(); 
foreach ($originalArray as $array) { 
    $tempArray[$array['catid']][] = $array['title']; 
} 
ksort($tempArray); 

$newArray = array(); 
while (count($tempArray)>0) { 
    foreach ($tempArray as $mKey => &$mArray) { 
    if (count($mArray)>0) 
     $newArray[] = array('title'=>array_shift($mArray),'catid'=>$mKey); 
    } 
    $tempArray = array_filter($tempArray); 
} 
+0

'+ 1' @crayonviolent偉大的答案!比我的更優雅。大聲笑 –

+0

太棒了!這就是我需要的! – luka

2

這是我想出來的一維數組,但它也應該爲2d工作。

$array = [1, 2, 2, 1, 3, 2, 3, 2, 1]; 

sort($array); 

$newarray; 


do{ 
    $max= max($array); 
    for($a = 0; $a <= $max; $a++){ 
     foreach($array as $key => $value){ 
      if($value == $a){ 
       $newarray[] = $value; 
       unset($array[$key]); 
       break; 
      } 
     } 
    } 

}while(!empty($array)); 

1, 2, 2, 1, 3, 2, 3, 2, 1 

將成爲:

1, 2, 3, 1, 2, 3, 1, 2, 2