Jump to content

Stacking in 3s


takn25

Recommended Posts

Hi, I want to know is there a simpler of achieving this. I have a table called part it has a row called HD.

The HD stores a number which is not unique. I will provide a visual example below to explain further.               

 

Table

  HD           

  42             

  42             

  42               

 

What I am after is a query something like Pile HD in stacks of 3. For example there are 3 HD with the number 42. That is 1 stack if there were 6 HD with the number 42 that would equal 2 stacks and so on. I can do some sort of maths to get the results but would like to know is there a query I can come up with to show how many stacks of 3 are there? 

 

Link to comment
https://forums.phpfreaks.com/topic/234851-stacking-in-3s/
Share on other sites

I just puzzled a bit and this is what i came up with. Not sure if it is the cleanest way, but it works. Love to hear a better way though :)

Note though this assumes you first fetch data, and let php do the puzzling

<?php
$myarray = array(
    42,42,42,60,60,60,60,60,60,60,50,50,50,40,40,50
);
sort($myarray); // added this to sort unsorted arrays
$i = 0;

foreach($myarray as $key => $value){
    if ($key !== 0){$num = $key - 1;}else{$num=0;} //mainly for the first array element
    if($i <= 2 &&  $myarray[$num] == $value){ // if previous value is the same as the current
        echo $value.'<br />';
        $i++;        
    }else{
        echo '<hr>'.$value.'<br />';
        $i = 1;
    }
}
?>

 

p.s. what wine and some cheese can come up with :birthday:

 

edit: remove some redundant code ;)

edit2: added a sorting thingy

Link to comment
https://forums.phpfreaks.com/topic/234851-stacking-in-3s/#findComment-1207280
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.