如何在此 PHP 脚本中添加序列号列?

How to add serial number column in this PHP script?

我无法在此 php 脚本中输出序列号。 尝试为从 woocommerce 数据中获取的每个产品添加序列号。

<?php 
$args = array(
    'status' => 'publish',
    'limit' => 100,
    'orderby' => 'title',
    'order'   => 'ASC'
);
$products = wc_get_products( $args );
$counter = 0;

if (count($products)) {     
    // Open the table
    echo "<table style = 'background-color:#ffffff;border-collapse: collapse;'><thead><tr>
            <th width='40' style='border:1px solid black'>Sl No.</th>
            <th width='400' style='border:1px solid black'>Product Name</th>
            <th style='border:1px solid black' width='54'>Stock</th>
            </tr></thead>";
    // Cycle through the array
    foreach ($products as $product) {
        // Output a row
        echo "<tr>";
        echo "<td style='border:1px solid black'>$counter++</td>";
        echo "<td style='border:1px solid black'>$product->name</td>";
        echo "<td align='center' style='border:1px solid black'>$product->stock_quantity</td>";
        echo "</tr>";
    }

    // Close the table
    echo "</table>";
}


?>

PHP 无法解析字符串中的增量,所以你必须增加 $counter 显式:

$counter++;
echo "<td style='border:1px solid black'>$counter</td>";