PHP计算来自foreach循环的行

B0o*_*oMi 5 php foreach count

我在PHP中使用"foreach"循环来从我的MySQL数据创建表

我想要实现的是计算循环返回的行数

循环为每个"机器"创建新表,并将"契约"作为新行填充,但每当我尝试计算行时,它将从所有表中返回计数,而不是仅返回单个表.

这是我的代码:

<?php

foreach ($this->datatitle as $head) {

    $cards = 1;

    echo '<table id="cards" class="cards">';

    echo '<tr>';

    foreach ($this->datacount as $datacount) {

        echo '<td>' . $head->machine_text . ' ' . $head->machine_name . ' [' . $datacount->count . ']</td>';

    }

    echo '</tr>';
    echo '<tr>';
    echo '<td>';
    echo '<ul id="sortable" class="connectedSortable">';

    foreach ($this->data as $body) {

        if ($head->machine_text == $body->machine_text) {

            echo '<li class="ui-state-default">Auftrag: ' . $body->aufnr;
            echo '<br>' . $body->matnr . ' ' . $body->matxt;
            echo '<br>Menge ' . $body->gamng;
            echo '<br><br>';
            echo 'Start: ' . $body->gstrp;
            echo '<br>Ende: ' . $body->ssavd . '</li>';

            if ($cards++ == 10) {
                break;
            }

        } else {

        }

    }

    echo '</td>';
    echo '</tr>';
    echo '</table>';

}

?>
Run Code Online (Sandbox Code Playgroud)

$ cards定义了想要显示的行数,但我想计算未显示的行数.

tl; dr用foreach创建表,想要从单个表中计算行数

Nic*_*zee 4

在 foreach 循环之上,定义一个计数器。

$count = 0
Run Code Online (Sandbox Code Playgroud)

然后在你的 foreach 循环中:

$count = $count + 1
Run Code Online (Sandbox Code Playgroud)

在 foreach 循环之后:

echo $count
Run Code Online (Sandbox Code Playgroud)

例子:

<?php

foreach ($this->datatitle as $head) {

$count = 0;
$cards = 1;

echo '<table id="cards" class="cards">';

echo '<tr>';

foreach ($this->datacount as $datacount) {
    $count = $count + 1;
    echo '<td>' . $head->machine_text . ' ' . $head->machine_name . ' [' . $datacount->count . ']</td>';

}

echo '</tr>';
echo '<tr>';
echo '<td>';
echo '<ul id="sortable" class="connectedSortable">';

foreach ($this->data as $body) {

    if ($head->machine_text == $body->machine_text) {

        echo '<li class="ui-state-default">Auftrag: ' . $body->aufnr;
        echo '<br>' . $body->matnr . ' ' . $body->matxt;
        echo '<br>Menge ' . $body->gamng;
        echo '<br><br>';
        echo 'Start: ' . $body->gstrp;
        echo '<br>Ende: ' . $body->ssavd . '</li>';

        if ($cards++ == 10) {
            break;
        }

    } else {

    }

}

echo '</td>';
echo '</tr>';
echo '</table>';
echo $count;
}
?>
Run Code Online (Sandbox Code Playgroud)