1

2 つの特定のキーと値のペアを持つ配列の配列があります。私がやろうとしているのは、によって決定される上位 5 つの一意のcause値を取得することqtyです。つまり、causeキーを一意の値でグループ化し、原因ごとにqtyキーを合計して、上位 5 つの原因と各原因の合計数量を返します。

これが print_r(array_values($array)) が出力するものです。

Array ( 
[0] => Array ( [cause] => Other (please comment) [qty] => 0.417 ) 
[1] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.430 ) 
[2] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.430 ) 
[3] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.513 ) 
[4] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.513 ) 
[5] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.750 ) 
[6] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.750 ) 
[7] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.816 ) 
[8] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.816 ) 
[9] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.828 ) 
[10] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.828 ) 
[11] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.681 ) 
[12] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.681 ) 
[13] => Array ( [cause] => No Cause Selected [qty] => 0.918 ) 
[14] => Array ( [cause] => No Cause Selected [qty] => 0.918 ) 
[15] => Array ( [cause] => No Cause Selected [qty] => 0.926 ) 
[16] => Array ( [cause] => No Cause Selected [qty] => 0.937 ) 
[17] => Array ( [cause] => No Cause Selected [qty] => 0.809 ) 
[18] => Array ( [cause] => No Cause Selected [qty] => 0.809 ) 
[19] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.891 ) 
[20] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.891 ) 
[21] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.884 ) 
[22] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.884 ) ) 

よろしくお願いいたします。

4

2 に答える 2

2
<?php

// Total up the quantities
$totals = array();
$tally  = array();
foreach ($datapoints as $entry) {
    if (!isset($totals[$entry['cause']]) {
        $totals[$entry['cause']] = 0;
        $tally[$entry['cause']]  = 0;
    }
    $totals[$entry['cause']] += $entry['qty'];
    $tally[$entry['cause']]++;
}

// Sort them, 'descending' or 'reverse', so the larger entries are first
arsort($totals, SORT_NUMERIC);

// Take the first 5 entries from the sorted list
$top = array_slice($totals, 0, 5);

// Do something with it.
foreach ($top as $cause => $totalQty) {
    echo $cause . ': ' . $totalQty . ' with ' . $tally[$cause] . ' events' . PHP_EOL;
}

ただし、このデータがデータベースからのものである場合は、次のようなデータベースと SQL を使用することをお勧めします。

SELECT cause, SUM(qty) as totalQty, COUNT(qty) as tally
FROM data
GROUP BY cause
ORDER BY totalQty DESC
LIMIT 5;

代わりに、すべてのデータと処理を php にロードします。

于 2012-10-30T18:42:44.120 に答える
1

PHP 5.3+ を使用している場合は、コードでクロージャーを使用して並べ替えることができます (数量の降順)。

usort($arary,function($a,$b){
    return $b['qty'] - $a['qty']
}

この後、配列をループして最初の 5 つの固有値を取得できます。

于 2012-10-30T18:45:05.093 に答える