PHP排序按重量排序的多维数组
I just asked this question a moment ago but I asked incorrectly so I apologize.
I'm hoping there's an easy way to do this without tons and tons of loops.
I have a matrix in the following manner:
Foo1 Foo2 Foo3 .... FooN
Jan 1 8 5 4
Feb 10 12 15 11
Mar 12 7 4 3
Apr 10 16 7 17
Assuming the following array:
$arrayMonths = array(
'jan' => array(1, 8, 5,4)
'feb' => array(10,12,15,11)
'mar' => array(12, 7, 4, 3)
'apr' => array(10,16,7,17)
);
I need to sort the above array and show it in the following manner:
array[apr][FooN] = 17
array[feb][Foo3] = 15
array[mar][Foo1] = 12
array[jan][Foo2] = 8
Essentially, I need to get the greatest sum of the above weights, one month can only have one foo and one foo can only have one month. In the above example, the result would be 52.
Thanks
See Demo : http://codepad.org/vDI2k4n6
$arrayMonths = array(
'jan' => array(1, 8, 5,4),
'feb' => array(10,12,15,11),
'mar' => array(12, 7, 4, 3),
'apr' => array(10,16,7,17),
);
$position = array("Foo1","Foo2","Foo3","FooN");
$set = array();
foreach($arrayMonths as $key => $value)
{
$max = max($value);
$pos = array_search($max, $value);
$set[$key][$position[$pos]] = $max ;
}
function cmp($a, $b)
{
foreach($a as $key => $value )
{
foreach ($b as $bKey => $bValue)
{
return $bValue - $value ;
}
}
}
uasort($set,"cmp");
var_dump($set);
Output
array
'apr' =>
array
'FooN' => int 17
'feb' =>
array
'Foo3' => int 15
'mar' =>
array
'Foo1' => int 12
'jan' =>
array
'Foo2' => int 8
The PHP function max()
is the key here:
$sum = 0;
foreach ($array as $row) {
$sum += max($row);
}
echo $sum;
$totalArr = array();
$total = 0;
foreach($arrayMonths as $month => $row)
{
$high = max($row);
$totalArr[$month]['foo'] = $high;
$total += $high;
}
echo "Total is: " . $total . "
";
print_r($totalArr);
Outputs:
Total is: 52
Array
(
[jan] => Array
(
[foo] => 8
)
[feb] => Array
(
[foo] => 15
)
[mar] => Array
(
[foo] => 12
)
[apr] => Array
(
[foo] => 17
)
)
Use uasort()
if you want to sort the new array.
http://php.net/manual/en/function.uasort.php
Look into this way of doing it. http://www.php.net/manual/en/function.uasort.php
Input the array and a reference to a comparison function that you write yourself.
$arr_new = array();
foreach(array_keys($arrayMonths) as $h) {
$int_max = max($arrayMonths[$h]);
foreach(array_keys($arrMonths[$h]) as $h2)
if ($arrMonths[$h][$h2] == $int_max) {
$arr_new[$h]["foo{$h2}"] = $int_max;
break;
}
}