【问题标题】:PHP PDO retrieving json array from database - removing unwanted charsPHP PDO 从数据库中检索 json 数组 - 删除不需要的字符
【发布时间】:2016-04-17 19:19:33
【问题描述】:

我在数据库的一行中存储一个 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();

这给每个错误,并输出数组(不可用)如下:

[{"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

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

【问题讨论】:

    标签: php mysql arrays json pdo


    【解决方案1】:

    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);
    

    【讨论】:

      【解决方案2】:

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

      除此之外,我不确定你为什么要循环一个 json_encoded 数组,你不能这样做。

      • json_encode() 为 javascript 对象表示法格式化变量。
      • json_decode() 以 javascript 对象表示法从字符串(READ: string, not array)加载变量。

      为了更清楚:

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

      【讨论】:

        猜你喜欢
        • 2016-04-26
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多