从fetch(PDO::FETCH_ASSOC)创建一个字符串


Create a string from a fetch(PDO::FETCH_ASSOC)

我试图建立一个字符串从sql的结果,我不知道如何实现这一点时,从数据库的数据大于1。

当数据库的结果为1时,我能够做到这一点。

$result = $stmt_grade->fetch(PDO::FETCH_ASSOC);  
    $str ="[{$result['score_access']}, {$result['score_training']},
{$result['score_expectation']}, {$result['score_total']} ]";

但是当我需要循环fetch_assoc时,我无法为变量赋值或直接构建字符串。

while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
                 $resultcount['subarea'];

        }

我到处都找过了,没有找到任何解决方案或任何类似的方法来寻找灵感。我希望有人能帮助我。提前感谢!

最明显的方法是在while循环中遍历所有响应,并使用.=操作符不断地将其附加到字符串上。由于$result将为假,因此您可以判断记录何时用完。

我用换行符分隔每条记录。看起来您还想计算结果,所以我也添加了这一点。

$str = ""; // start with an empty string
$count = 0;
while ( ($result = $stmt_grade->fetch(PDO::FETCH_ASSOC)) !== false ) {
    // increment the record count
    $count++;
    // add a new line to the output string
    $str .= "[{$result['score_access']}, {$result['score_training']},{$result['score_expectation']}, {$result['score_total']} ]'n";
}

应该可以了

您所需要的只是来正确地命名您的字符串

然后用合适的方式创建一个JSON字符串。它由两部分组成:
  1. 创建所需结构的数组。或者至少在这里提供一个that结构,以便我们为您提供代码。
  2. 使用json_encode()。

假设你需要一个像这样的嵌套数组

[[1,2,3],[1,2,3],[1,2,3]]

代码应该是

$result = $stmt_grade->fetchAll(PDO::FETCH_NUM);  
echo json_encode($result);

感谢您提供的所有答案,没有您我不可能做到。最后,我得到了如下的理想结果,可能它并不优雅,但可以工作:

 $stmt_count= $user->countbyespeciality();
                while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
                    $prueba.= "{$resultcount['subarea']},";
                    $prueba2.= "{$resultcount['number']},";
            }
                $string=rtrim($prueba, ",");
                $string2=rtrim($prueba2, ",");
                $final="[{$string}]";
                $final2="[{$string2}]";

输出如预期为[某物,某物][1,2,]。再次感谢!