【问题标题】:PHP - output associate array into HTML <div>s with labels/headingsPHP - 将关联数组输出到带有标签/标题的 HTML <divs
【发布时间】:2016-02-05 17:17:03
【问题描述】:

我有一个 PHP 函数,它从本地 MySQL 表返回单行,如下所示:

<?php
//include database connection process
require_once("includes/conn.inc.php");
//prepare statement
$stmt = $conn->prepare("Select * FROM races WHERE raceID = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
?>

我想用这个数组做的是从他们自己的 HTML &lt;div&gt;&lt;p&gt; 中输出各个字段的数据,并带有一个标题,表明它们在单独的 div 中的含义。我目前使用print_row 方法,将所有内容合二为一。我想要的所有数据都在那里,但我希望将其分成名称/值段落或 div。

//what I currently have
<?php
    print_r($row);
?>

有没有办法做到这一点?

提前致谢,

标记

【问题讨论】:

    标签: php html mysql


    【解决方案1】:

    我不太明白这个问题,但我想我明白你需要什么。

    使用 while 遍历每一行。

    while($row = $resultDesc->fetch_assoc())
    {
        echo '<p><strong>Description:</strong></p> ';
        echo '<p>'. $row['description'] . '</p>';
    }
    

    这不是确切的解决方案,但至少可以为您指明路径。

    【讨论】:

      【解决方案2】:

      您可以使用foreach

      <?php foreach ($row as $key => $val): ?> 
          <p><strong><?php echo $key; ?>:</strong></p> 
          <p>
              <?php
                  //output relevant attribute
                  //of query run on page load
                  echo $val;
              ?>
          </p>
      <?php endforeach; ?>
      

      【讨论】:

      • 嗨,我意识到我的问题措辞不当,虽然它回答了我的问题,但并没有得到我想要的。你介意看看我更新的问题吗?谢谢
      • 我不明白,但你想要。我已经认为我的答案就是您要的...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多