我的弦变成了字母数组

时间:2019-07-08 12:53:02

标签: php mysql arrays json string

我已从数据库中提取数据。但是,当我从数组中回显特定值时,该字符串将显示为数组,每个字母都用自己的索引分隔!

我尝试内爆,但出现一个错误,即我传递的参数不正确,并且爆炸不会改变任何事情。

 $stmt = $conn->prepare("SELECT * FROM cours WHERE date = :date AND time = :time AND cours = :cours AND present ='non'");
 $stmt->execute([':date' => $date, ':cours' => $cours, ':time' => $time]);

 if ($stmt->rowCount() > 0) {
    $output = $stmt->fetchAll();

        $classe = $output[0]['classe'];
        // explode(",",$classe);
        // implode(",",$classe);
        echo json_encode($classe);

 } else {
    $errors = "No data found for this date";
    echo json_encode($errors);
 }

控制台中的结果是

[object Array]: ["W", "i", "n", "t", "e", "r", " ", "2", "0", "1", "9"]
0: "W"
1: "i"
2: "n"
3: "t"
4: "e"
5: "r"
6: " "
7: "2"
8: "0"
9: "1"
10: "9"
length: "11"

您可以在上面的控制台日志中看到我得到的结果。我需要以字符串格式将其作为一个值。

1 个答案:

答案 0 :(得分:2)

您可以直接在查询中进行操作(使用GROUP_CONCAT()),但是如果您想要使用PHP解决方案,则只需implode(),而无需使用分隔符即可对它进行编码。

虽然仅使用第一行,fetchAll()似乎毫无意义?您可以执行$output = $stmt->fetch();,然后执行$classe = $output['classe'];(如果您更改查询以仅返回fetchColumn()列,甚至可以使用classe)。

if ($output = $stmt->fetchAll()) {
    $classe = $output[0]['classe'];
    // explode(",",$classe);
    $classe = implode("", $classe);
    echo json_encode($classe);
} else {
    $errors = "No data found for this date";
    echo json_encode($errors);
}

通过使用GROUP_CONCAT(),您将在查询中完成所有操作,

$stmt = $conn->prepare("SELECT GROUP_CONCAT(classe SEPARATOR '') as allClasse FROM cours WHERE date = :date AND time = :time AND cours = :cours AND present ='non'");
$stmt->execute([':date' => $date, ':cours' => $cours, ':time' => $time]);

if ($row = $stmt->fetch()) {
    echo json_encode($row['allClasse']);
} else {
    $errors = "No data found for this date";
    echo json_encode($errors);
}