PHP PDO从数据库中检索json数组-删除不需要的字符


PHP PDO retrieving json array from database - removing unwanted chars

我正在数据库中的一行中存储一个JSON数据数组,并试图检索该数组以便在foreach循环中使用。

下面的代码是我将用于foreach循环的代码,但我在实际检索数据时遇到了一些问题,需要使用PDO。

$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $data){
    echo $data['id'];
}

我遇到的问题是使用PDO检索要放入$data的数组。目前我有这个查询和代码,其输出如下。

$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
                $statement->bindParam(':c_s', $c_s);
                $statement->execute();
                $data = $statement->fetchAll();
$result = json_encode($data, true);
                return $result;

混合以下代码显示数组:

foreach ($result as $key) {
            echo $key['id'];
        }
        print_r($result);
        die();

这为for each提供了一个错误,并将数组(不可用)输出如下:

[{"gp":"[{'"id'":'"H592736029375'"},{'"id'":'"K235098273598'"},{'"id'":'"B039571208517'"}]","0":"[{'"id'":'"H592736029375'"},{'"id'":'"K235098273598'"},{'"id'":'"B039571208517'"}]"}]

作为我拥有的第一段代码,我可以根据需要使用数据。我只需要一些指导,告诉你如何正确地从数据库中获取数组,然后在foreach中使用。

我知道我目前使用的是json_encode而不是json_decode,使用json_decode会出现以下错误:

Warning: json_decode() expects parameter 1 to be string, array given

对于我的错误建议将不胜感激

fetchAll()返回一个行数组,而不是您期望的单个字段:

$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$rows = $statement->fetchAll();
$data = $rows[0]['gp'];
$result = json_decode($data);

您期望$data是一个字符串,而它是一个数组。使用$statement->fetchColumn()检索单个字段或使用json_decode($data['gp'])

除此之外,我不太清楚为什么要在json_encoded数组上循环,你不能这样做。

  • json_encode()为javascript对象表示法格式化变量
  • json_decode()从javascript对象表示法中的字符串(READ:string,而不是数组)加载变量

让它更加清晰:

  • 使用json_encode()在mysql中插入数据
  • 使用json_decode()将一列放回相应的php变量/状态