我想获得一个值,但它会出现两次:
<?php
session_start();
$username = $_SESSION['user'];
include 'connect.php';
if (isset($_GET['var'])) {
$var = $_GET['var'];
echo "<br>";
echo $var;
$pieces = explode(",", $var);
foreach ($pieces as $i) {
$sql = "SELECT title FROM interests WHERE id = '$i' ";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
}
$value = join(",", $row);
}
echo $username;
echo $value;
?>
它出现为:result, result
;它应该只作为1结果而不重复
答案 0 :(得分:2)
mysqli_fetch_array
同时返回数字索引和关联数组。这意味着您可以获得同一数组中每个字段的两个副本(一个用数字索引,一个用名称索引)。将对此的调用更改为仅获取关联数组:
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
关于下面评论中讨论的第二个问题,请尝试以下方法:
$titles = [];
foreach ($pieces as $i) {
$sql = "SELECT title FROM interests WHERE id = '$i' ";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$titles[] = $row["title"];
}
$value = join(",", $titles);