对数组进行分组和排序

时间:2011-10-18 11:58:22

标签: php

我有一个数组

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 FIELD对数组进行分组,即我应该返回一个分组的数组

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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

简单如馅饼

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

以后你将$ groupedArray与所有组及其值作为数组