2011-10-18 68 views
0

我有一個數組分組和排序的陣列

Array 

(

    [0] => Array 
     (
      [sub] => 
      [OWNER] => owner1 
      [cnt] => 0 
      [ST_STATUS] => 
     ) 

    [1] => Array 
     (
      [sub] => 
      [OWNER] => owner1 
      [cnt] => 3675 
      [ST_STATUS] => No Run 
     ) 

    [2] => Array 
     (
      [sub] => 
      [OWNER] => owner2 
      [cnt] => 416 
      [ST_STATUS] => No Run 
     ) 

    [3] => Array 
     (
      [sub] => 
      [OWNER] => owner3 
      [cnt] => 273 
      [ST_STATUS] => No Run 
     ) 

    [4] => Array 
     (
      [sub] => 10/1/2011 
      [OWNER] => owner2 
      [cnt] => 14 
      [ST_STATUS] => No Run 
     ) 

    [5] => Array 
     (
      [sub] => 10/10/2011 
      [OWNER] => owner3 
      [cnt] => 1 
      [ST_STATUS] => Failed 
     ) 

    [6] => Array 
     (
      [sub] => 10/10/2011 
      [OWNER] => owner3 
      [cnt] => 11 
      [ST_STATUS] => No Run 
     ) 

} 

欲組由所有者字段的數組,它是我應返回其由OWNER

值進行分組

陣列。 這樣

array([0] => Array 

     (

      [sub] => 
      [OWNER] => owner1 
      [cnt] => 0 
      [ST_STATUS] => 
     ), 


[1] => Array 

     (

      [sub] => 
      [OWNER] => owner1 
      [cnt] => 0 
      [ST_STATUS] => 
     ) 

[2] => Array 
     (


      [sub] => 
      [OWNER] => owner1 
      [cnt] => 0 
      [ST_STATUS] => 
     ), 



[3] => Array 
     (
      [sub] => 
      [OWNER] => owner2 
      [cnt] => 0 
      [ST_STATUS] => 
     ), 


[4] => Array 
     (
      [sub] => 
      [OWNER] => owner2 
      [cnt] => 0 
      [ST_STATUS] => 
     ) 

回答

2
$temp = $result = array(); 
foreach ($array as $sub) { // Put original array into OWNER groups 
    $temp[$sub['OWNER']][] = $sub; 
} 
ksort($temp); // Sort by OWNER name 
foreach ($temp as $group) { // Put sorted array back into correct format 
    foreach ($group as $sub) { 
    $result[] = $sub; 
    } 
} 
unset($temp); 
print_r($result); 

...或替代辦法...

// create an array for the columns 
$owner = array(); 
foreach ($array as $rowid => $rowdata) { 
    $owner[$rowid] = $rowdata['OWNER']; 
} 
// Sort it 
array_multisort($owner,SORT_ASC,$array); 
0

易如反掌

$originalArray = your_value; 
$groupedArray = array(); 
foreach($originalArray as $value){ 
    $groupedArray[$value['OWNER']][] = $value 
} 

,以後你有$ groupedArray所有團體和他們的值作爲陣列