Foreach 循环不会根据列名回显正确的文本

我的数据库中有 2 个表。表tableA看起来像这样:


 taid | tanum | tarelation

---------------------------

  30  |  22   |  101

  31  |  88   |  101

表格tableB如下所示:


 tbid | tbnum | tbrelation

---------------------------

  1   |  10   |  101

  2   |  20   |  101

这是我的代码:


<?php

$columns = [];

$stmt = $conn->prepare("

    SELECT tanum FROM tableA

    UNION ALL

    SELECT tbnum FROM tableB;

  ");

$stmt->execute();

$result = $stmt->get_result();

while($row = $result->fetch_object()) {

  $columns[] = $row;

}

$stmt->close();

?>


<?php foreach($columns as $column): ?>

    <?php if ($column->tanum): ?>

        <div><?php echo $column->tanum; ?>tanum</div>

    <?php elseif ($column->tbnum): ?>

        <div><?php echo $column->tbnum; ?>tbnum</div>

    <?php endif; ?>

<?php endforeach; ?>

所以这是我想要达到的结果:


22tanum

88tanum

10tbnum

20tbnum

但这是我根据我当前的代码得到的结果:


22tanum

88tanum

10tanum

20tanum

如您所见,基于if statement, 如果$column->tanum被回显,则该词tanum应该出现在它之后;如果$column->tbnum被回显出来,那么单词tbnum应该出现在它之后。但相反,只tanum显示单词。代码有什么问题?请帮忙,谢谢


德玛西亚99
浏览 170回答 2
2回答

慕侠2389804

&nbsp;aUNION中的列名是由第一次选择的列名设置的,因此您永远不会看到$column->tbnum值。要解决此问题,您可以将第二列添加到作为列名称的选择中。例如:$columns = [];$stmt = $conn->prepare("&nbsp; &nbsp; SELECT tanum, 'tanum' AS cname FROM tableA&nbsp; &nbsp; UNION ALL&nbsp; &nbsp; SELECT tbnum, 'tbnum' FROM tableB;&nbsp; ");$stmt->execute();$result = $stmt->get_result();while($row = $result->fetch_object()) {&nbsp; $columns[] = $row;}$stmt->close();?><?php foreach($columns as $column): ?>&nbsp; &nbsp; <div><?php echo $column->tanum . $column->cname; ?></div><?php endforeach; ?>

慕森王

你需要重构你的代码。<?php$columns = [];$stmt = $conn->prepare("&nbsp; &nbsp; SELECT tanum, 'a' as ident FROM tableA&nbsp; &nbsp; UNION ALL&nbsp; &nbsp; SELECT tbnum, 'b' as ident FROM tableB;&nbsp; ");$stmt->execute();$result = $stmt->get_result();$i = 0;while($row = $result->fetch_object()) {&nbsp; $columns[$i]['tanum'] = $row['tanum'];&nbsp; $columns[$i]['ident'] = $row['ident'];&nbsp; $i++;}$stmt->close();?><?php foreach($columns as $column): ?>&nbsp; &nbsp; <?php if ($column['ident']=='a') ?>&nbsp; &nbsp; &nbsp; &nbsp; <div><?php echo $column['tanum']; ?>tanum</div>&nbsp; &nbsp; <?php elseif ($column['ident']=='b') ?>&nbsp; &nbsp; &nbsp; &nbsp; <div><?php echo $column['tanum']; ?>tbnum</div>&nbsp; &nbsp; <?php endif; ?><?php endforeach; ?>
打开App,查看更多内容
随时随地看视频慕课网APP