Php为每个循环双重结果

时间:2017-01-18 16:17:42

标签: php

我对PHP很新,并尝试构建一个Web应用程序。 这个 foreach 循环在两个单独的行中输出两个结果,而不是在下面的表格元素中输出一个(即 td ):

 <td><?=$item['title'];?></td>
    <td><?=$item['category'];?></td>

这是我的代码:

<?php 
      $iQuery = $db->query("SELECT * FROM products WHERE deleted = 0");
      $lowItems = array();
        while($product = mysqli_fetch_assoc($iQuery)){
                $item = array();
                $sizes = sizesToArray($product['sizes']);
                foreach($sizes as $size){
                    if ($size['quantity'] <= $size['threshold']) {
                        $cat = get_category($product['categories']);
                        $item = array(
                            'title' => $product['title'],
                            'size' => $size['size'],
                            'quantity' => $size['quantity'],
                            'threshold' => $size['threshold'],
                            'category' => $cat['parent'] . ' ~ ' .$cat['child']
                        );
                        $lowItems[] = $item;
                    }
                }
        }

    ?>

    <div class="col-md-8">
    <h3 class="text-center">Low Stock</h3>
    <table class="table table-condensed table-striped table-bordered">
        <thead>
            <th>Product</th>
            <th>Category</th>
            <th>Size</th>
            <th>Quantity</th>
            <th>Threshold</th>
        </thead>
        <tbody>
        <?php foreach($lowItems as $item): ?>
            <tr<?=($item['quantity'] == 0)?' class="danger"':'';?>>
                <td><?=$item['title'];?></td>
                <td><?=$item['category'];?></td>
                <td><?=$item['size'];?></td>
                <td><?=$item['quantity'];?></td>
                <td><?=$item['threshold'];?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</div>

其余的表格单元格只显示一次 - 只有两个第一个重复显示两次。

size to Array function:

function sizesToArray($string){
    $sizesArray = explode(',', $string);
    $returnArray = array();
    foreach($sizesArray as $size){
        $s = explode(':',$size);
        $returnArray[] = array('size' => $s[0], 'quantity' => $s[1],'threshold' => $s[2]);
    }
    return $returnArray;    
}

这是$ LowItems的var转储:

array(3) {
    [0]=> array(5) {
        ["title"]=> string(6) "Tshirt"
        ["size"]=> string(5) "Small"
        ["quantity"]=> string(1) "2"
        ["threshold"]=> string(1) "5"
        ["category"]=> string(12) "Men ~ Shirts"
    }
    [1]=> array(5) {
        ["title"]=> string(6) "Tshirt"
        ["size"]=> string(0) ""
        ["quantity"]=> NULL
        ["threshold"]=> NULL
        ["category"]=> string(12) "Men ~ Shirts"
    }
}

1 个答案:

答案 0 :(得分:0)

更改

if ($size['quantity'] <= $size['threshold']) {

if ($size['size'] && $size['quantity'] <= $size['threshold']) {