Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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:

    Weight1 Weight2 Weight3 .... WeightN
Jan    1       3       5            4
Feb    10      12      15          11
Mar    5       7       4            3
Apr    10      15      7            3

Assuming the following array:

$arrayMonths = array(
       'jan' => array(1, 3, 5,4)
       'feb' => array(10,12,15,11)
       'mar' => array(5, 7, 4, 3)
       'apr' => array(10,15,7,3)
    );

What is the best way for me to get the the max for each row: jan = 5 feb = 15 mar = 7 apr = 15

Thanks

share|improve this question
1  
What have you tried? –  Jack Maney Apr 27 '12 at 6:24
add comment

4 Answers

Use the max() function:

foreach($arrayMonths as $month => $row)
{
    echo $month . ": " . max($row) . "<br />";
}
share|improve this answer
add comment
foreach ($arrayMonths as $month => $array) {
    // store the max of each month for later
    // $max['jan'] = 5
    $max[$month] = max($array);

    // or print it out
    echo $month. ' => '. max($array);
}

From the max() PHP Docs

If you need to go further with sorting you can check out here for more information PHP Array Sorting

share|improve this answer
add comment

Try this:

<?php
function getMax( $v, $k ) {
    global $arrayMonths;

    $arrayMonths[ 'max' ][$k] = max($v);
}

$arrayMonths = array(
   'jan' => array(1, 3, 5,4),
   'feb' => array(10,12,15,11),
   'mar' => array(5, 7, 4, 3),
   'apr' => array(10,15,7,3)
);

array_walk( $arrayMonths, 'getMax' );

// Now $arrayMonths['max'] will contain all max values for each key
?>

Hope this helps.

share|improve this answer
add comment
up vote 0 down vote accepted

I found the perfect algorithm: Basically use a recursive function which goes through all permutations.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.