while循环仅显示元素x次

时间:2019-06-30 10:15:25

标签: php

我有这个扩大/结束的部门。我将有一个类别标题(只显示一次),下面有子类别信息(需要循环x次)。一切(某种)工作正常,除了我需要子类别信息以遍历其存在的次数。

目前为止,这是到目前为止我得到的结果:https://imgur.com/a/nAg2Uhd

如您所见,它正在关闭标签,再次循环并在

下添加子类别
$result_array = mysqli_query($connect,"SELECT * FROM tbl_customer, categories WHERE tbl_customer.category_QA = categories.id ORDER BY Category ASC");
    $checkCategory = '';

    while($data = mysqli_fetch_array($result_array)){


   //works as it shows the category once
       if  ($checkCategory != $data["Category"]){


    echo'           
    <div class="collapse-group">
              <div class="collapse-item">
                <div class="collapse-head">
                      '.$data["Category"].'
                </div>
                <div class="collapse-content">';


      }


    //Here is where I need to loop through all sub category data and display them 
     echo '    <p>  '.$data["productName"].'</p>';



      //Should only run once all sub category data has been displayed 
      //close all tags 
      if  ($checkCategory != $data["Category"]){

    echo    '
                      </div>
                 </div>
              </div>';

        $checkCategory = $data["Category"];


      }

    }

1 个答案:

答案 0 :(得分:0)

您需要正确地编写标签,而不是

'            <
            div class = "collapse-group" >

您需要

'<div class = "collapse-group">

,而不是

' <
            /div>

您需要

' </div>

这应该可以解决错误,但我还将为您提出一种更好的方法。首先,您需要确保它是可重用的,因此,请确保它在function中。其次,您需要确保代码生成与显示分开:

function generateCategories($result_array) {
    $checkCategory = '';
    $output = array();
    $index = -1;
    while ($data = mysqli_fetch_array($result_array)) {
        if ($checkCategory != $data["Category"]) {
            $checkCategory = $data["Category"];
            $output[]=array("key" => $checkCategory, "values" => array());
            $index++;
        }
        $output[$index]["values"][]=$data["productName"];
    }
    return $output;
}

function generateCategoryStructure($input) {
    $output = "";
    for ($index = 0; $index < count($input); $index++) {
        $output .= '<div class = "collapse-group">'.
                       '<div class = "collapse-item">'.
                           '<div class = "collapse-head">'.$input[$index]["key"].'</div>'.
                           '<div class = "collapse-content">';
        for ($innerIndex = 0; $innerIndex < count($input[$index]["values"]); $innerIndex++) {
            $output .=         '<p>'.$input[$index]["values"][$innerIndex].'</p>';
        }
        $output .=         '</div>'.
                       '</div>'.
                   '</div>';
    }
}

然后:

echo generateCategoryStructure(generateCategories($result_array));