将结果合并到一个爆炸的表格行中

时间:2016-02-09 01:33:15

标签: php mysql

我有以下代码:

<?php

while ($rows = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $combi = explode(",", $rows['keyword_id']);
    foreach($combi as $keyword_ids) {
        $sql = "SELECT keyword from keyword where keyword_id = '$keyword_ids'";
        $results = mysqli_query($con, $sql) or die("Error: " + mysqli_error($con));
        while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
            $keyword_name = $row['keyword'];

            // $data[] = $row['keyword'];
            // $keyword_name = implode(', ', $data);

        }
    }

    echo '<tr>';
    echo '<td class="telco_name">' . $rows['name'] . '<input type="hidden" class="cross_sell_id" value=' . $rows['id'] . '> <input type="hidden" class="telco_id" value=' . $rows['tid'] . ' > </td>';
    echo '<td class="keyword_name">' . $keyword_name . ' <input type="hidden" class="keyword_id" value=' . $rows['keyword_id'] . ' > </td>';
    echo '<td class="main_cross" style="width:100px;">' . $rows['main_message'] . '</td>';
    echo '<td class="alternate_cross">' . $rows['alternate_message'] . '</td>';
    echo '<td class="start_date">' . $rows['start_timestamp'] . ' </td>';
    echo '<td class="end_date">' . $rows['end_timestamp'] . ' </td>';

我希望输出的内容是这样的

<tr>
    <td> keyword_name, keyword_name </td>
    <td> keyword_name </td>
<tr>

我将如何做到这一点?

从db保存的数据。 keyword_id以逗号分隔。

1 个答案:

答案 0 :(得分:0)

由于您已经在逗号分隔的字符串中使用了ID,因此您可以使用 IN 来获取一个查询中的所有关键字。

while ($rows = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $sql = "SELECT keyword_id,keyword from keyword where keyword_id IN ({$rows['keyword_id']})";
    $results = mysqli_query($con, $sql) or die("Error: " + mysqli_error($con));
    $keywords = [];
    while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
        $keywords[$row['keyword_id']] = $row['keyword'];
    }
}

/* This line should display the keywords and set the value to the ids
 * however, it lacks both an id (for client side use) and a name (to 
 * send to the server)
 */
echo '<td class="keyword_name">' . implode(', ',$keywords) . ' <input type="hidden" class="keyword_id" value=' . implode(',',array_keys($keywords)) . ' > </td>';