0

I have a results table which I iterate over and then echo out.

$c = 1;
foreach ($results as $result) {
    $r .= '<tr>'
    . '<th scope="row">' . ($time === $result['time']? $c - 1 : $c)  . '</th>'
    . '<td>' . $result['name'] . '</td>'
    . '<td>' . $result['time'] . ' </td>'
    . '<td>' . $result['points'] . ' </td>'
    . '</tr>';

    $time = $result['time'];
    $c++;
}

I compare the current time with the previous result time and display the count the same if they match. e.g.
1. Tom 0.33
2. Ben 0.34
2. Carl 0.34
4. Des 0.35
5. Dave 0.36

But what if Des had also got 0.34? It would display count 3 and it should stay on 2.

Any ideas how to solve this without getting too complex?

4

4 回答 4

2
$c = 1;
$lastC = $c;
foreach ($results as $result) {

    if ($time === $result['time']) {
        $place = $lastC;
    } else {
        $place = $c;
        $lastC = $c;
    }

    $r .= '<tr>'
    . '<th scope="row">' . $place  . '</th>'
    . '<td>' . $result['name'] . '</td>'
    . '<td>' . $result['time'] . ' </td>'
    . '<td>' . $result['points'] . ' </td>'
    . '</tr>';

    $time = $result['time'];
    $c++;
}
于 2013-07-17T14:12:46.460 回答
1

这是因为你让它只减 1。

$c - 1

你会想要一个像你一样的计数器,但需要一个当前行。就像是

$c = 1;
$curr = $c;
foreach( $results as $result){
  if($time === $result['time']){
    use $curr;
  }else{
    use $c;
    $curr = $c + 1;
  }
  $c++;
}

但是如果你移动 $c++,你可以将它与 $curr 绑定,比如

$c++;
$curr = $c;
于 2013-07-17T14:10:13.720 回答
0
function compare($one, $two)
{
    $a = $one['time'];
    $b = $two['time'];

    if ($a == $b) {
        return 0;
    }

    return ($a < $b) ? -1 : +1;
}


$array = array(
    array('name' => 'Tom', 'time' => '0.33', 'points' => 1),
    array('name' => 'Ben', 'time' => '0.36', 'points' => 1),
    array('name' => 'Carl', 'time' => '0.35', 'points' => 1),
    array('name' => 'Des', 'time' => '0.33', 'points' => 1),
    array('name' => 'Dave', 'time' => '0.34', 'points' => 1)
);

usort($array, 'compare');

print_r($array);
于 2013-07-17T14:26:41.090 回答
-1

你在你的短时间里做一个准时的数学运算。您必须使结果永久化:

$c = 1;
foreach ($results as $result) {
    if($time === $result['time'])
      $c--;
    $r .= '<tr>'
    . '<th scope="row">' . $c  . '</th>'
    . '<td>' . $result['name'] . '</td>'
    . '<td>' . $result['time'] . ' </td>'
    . '<td>' . $result['points'] . ' </td>'
    . '</tr>';

    $time = $result['time'];
    $c++;
}
于 2013-07-17T14:22:23.180 回答