saiyan101
saiyan101

Reputation: 620

Php: Array Top 5 sorting

I have created an array that fetches the Top 5 values. For example Tom = 5,Jill = 5,Jack = 3, Jim = 2, Joe = 2 Tom and Jill share position 1 Jack get position 2 Jim and Joe = 3

I have managed to sort them but I can not seem to get them to share the position, problem is Tom gets position 1 and Jill gets position 2 and Jack gets 3. I would like the values to group then I sort by group position.

$people = array(
    "5##Tom",
    "5##Jill",
    "3##Jack", 
    "2##Jim", 
    "2##Joe"
);

foreach( $people as $key => $value){
    $cellTD = array();
    $cellTD = explode("##",$value);

    if(!empty($cellTD[1])) {
        //Give me top 5
        if($key <= 4){
            echo '<tr>';
            echo '<td style="border: 1px solid #ccc;text-align:right;font-weight:bold;" width="20%">'.($key+1).'</td>'; 
            echo '<td style="border: 1px solid #ccc;" width="50%">'.$cellTD[1].'</td>';
            echo '<td style="border: 1px solid #ccc;" width="20%">'.$cellTD[2].'</td>';
            echo '<td style="border: 1px solid #ccc;text-align:right;" width="20%">'.numFormat($cellTD[0]).'</td>';   
            echo '</tr>';
        }
    }
}

I would like to use only php array and not mysql to sort and group.

Upvotes: 0

Views: 69

Answers (1)

M. Eriksson
M. Eriksson

Reputation: 13635

You need to store the value from the last iteration and compare it with the current value.

$position = 0;
$previous = 0;

foreach( $people as $value){
    $cellTD = array();
    $cellTD = explode("##",$value);

    if ($cellTD[0] != $previous) {
        // Since the value is different, increment the position
        $position++;
    }

    $previous = $cellTD[0];

From now on, you can use $position to show the position instead of $key+1.

But as others have pointed out, your $cellTD will be an array with two elements (0 and 1) so $cellTD[2] should give you an "Undefined index" warning.

I'm letting you sort out the rest of the table (since it seems like you're trying to output more data than the array you posted contains).

Upvotes: 1

Related Questions