【问题标题】:Getting database table column name duplicates in PHP loop [closed]在PHP循环中获取数据库表列名重复[关闭]
【发布时间】:2019-08-09 19:50:43
【问题描述】:

在我的 for each 循环中打印出列名,因为某些原因,我得到了重复的名称和数字。

$q = "SELECT products.name, products.price, products.amount, categories.category_name 
      FROM products 
        LEFT JOIN categories ON (products.category_id = categories.category_id)";

<table class="table">
  <thead>
    <tr>
        <?php while ($row = mysqli_fetch_array($query)) {

        foreach ($row as $key => $value) {
            echo "<th scope='col'>$key</th>";
            }
        } ?>
    </tr>
  </thead>

我的表中有 3 个产品,我得到 3 个重复的列名

【问题讨论】:

  • secure.php.net/manual/en/mysqli-result.fetch-array.php: “获取结果行作为关联,数字数组,或两者 - 你目前正在做后者,因为 MYSQLI_BOTH 是默认模式。
  • 我很惊讶你得到了什么!因为您不提交该查询以在任何地方执行
  • @RiggsFolly 我愿意,我只是不包含我的问题不需要的代码
  • &lt;?php while ($row = mysqli_fetch_assoc($query)) {
  • $i = 1; foreach ($row as $key =&gt; $value) { if($i &gt; 1){ continue ;} echo "&lt;th scope='col'&gt;$key&lt;/th&gt;"; $i++; }

标签: php mysql loops foreach


【解决方案1】:

如果你想使用动态的列名,那么你可以将你的数据存储到一个新的数组中,然后你可以使用这个数组两次,一次用于标题,一次用于值。

$newArray = array(); // initiliaze
while ($row = mysqli_fetch_assoc($result)) { // here i am using mysqli_fetch_assoc
    $newArray[] = $row;  // store in a new array
}

那么,你的标题为:

$i = 1;
foreach ($newArray as $value) {
    if($i > 1) continue; // will use for ist iteration only.
    foreach ($value as $key => $Fvalue) {
        echo "<th scope='col'>".$key."</th>"; // will print headings            
    }   
    $i++;
}

那么你可以像这样显示你的价值观:

foreach ($newArray as $value) {
    foreach ($value as $key => $Fvalue) {
        echo "<td>".$Fvalue."</td>";    // will show all values.                
    }       
}

【讨论】:

  • 感谢您的明确回答,我一直在使用您的代码,以了解每个部分。我知道你如何使用continue 只打印一次标题并跳过循环的其余部分,但我认为你也可以在这里使用break 而不是continue,是吗?而且我仍然不明白为什么没有continue,标题的迭代会重复多次。为什么它会这样,而值的循环很好并且不重复?
  • continue 表示,continue 后不会执行任何脚本 @Limpuls
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多