PHP从sql查询中获取值(使用implode / explode?)

时间:2016-11-21 06:28:09

标签: php sql

我正在运行以下查询。我可以使用ticket_cost结果列,但我很难理解如何从结果中提取其他数据。

$sql = "SELECT ticket_cost, GROUP_CONCAT(game ORDER BY game DESC SEPARATOR '|') FROM games WHERE id IN (" . implode(',', $myIDArray) . ") GROUP BY ticket_cost ORDER BY ticket_cost DESC";
$myresult = mysqli_query($connection,$sql);

结果在phpmyadmin中看起来像这样:

ticket_cost   |   GROUP_CONCAT(game ORDER BY game DESC SEPARATOR '|')
    10            thisIsATest|thisIsATest2|thisIsATest3
    5             thisIsAnotherTest

要显示,我正在使用:

echo "<ul>";
foreach($myresult as $row2)
    {
        echo "This doesn't work:" . $row2['game'];
        echo "<li>" . $row2['ticket_cost'] . "</li>";
    }
echo "</ul>";

显示:
这不起作用:
10个
5

如何在每个ticket_cost之后显示每个管道(“|”)分隔的结果项?

2 个答案:

答案 0 :(得分:1)

使用别名

<强>查询

$sql = "SELECT ticket_cost, GROUP_CONCAT(game ORDER BY game DESC SEPARATOR '|') AS gameData FROM games WHERE id IN (" . implode(',', $myIDArray) . ") GROUP BY ticket_cost ORDER BY ticket_cost DESC";
$myresult = mysqli_query($connection,$sql);

PHP代码

echo "<ul>";
foreach($myresult as $row2)
{
    $gameData = explode("|", $row2['gameData']);
    foreach($gameData as $row3)
    {
        echo "<li>" . $row3 . "</li>";
        echo "<li>" . $row2['ticket_cost'] . "</li>";
    }
}
echo "</ul>";

<强>输出

ticket_cost       GameData
-----------       -----------
    10            thisIsATest
    10            thisIsATest2
    10            thisIsATest3
    5             thisIsAnotherTest

答案 1 :(得分:0)

您也可以在不修改查询的情况下访问该数据。访问结果时,请使用mysqli_result::fetch_array()

访问该值

PHP代码

echo '<ul>';
while($row2 = $myresult->fetch_array())
{
    // Your game data is the 2nd value in your select, so
    // access it with the 0-based index of [1]
    $gameData = explode('|', $row2[1]);
    foreach ($gameData as $game)
    {
        echo '<li>' . $game . ' $'. $row2['ticket_cost'] . '</li>';
    }
}

<强>输出

  • thisIsATest $ 10
  • thisIsATest2 $ 10
  • thisIsATest3 $ 10
  • thisIsAnotherTest $ 5