我在数据库的一行中存储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
非常感谢我对错误的建议
答案 0 :(得分:4)
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);
答案 1 :(得分:1)
您希望$data
成为字符串,而它是一个数组。使用$statement->fetchColumn()
来检索单个字段或使用json_decode($data['gp'])
除此之外,我不完全确定你为什么要循环json_encoded数组,你不能这样做。
json_encode()
格式化javascript对象表示法的变量。json_decode()
以javascript对象表示法从字符串( READ:字符串,而不是数组)加载变量。让它更清晰:
json_encode()
在mysql中插入数据。json_decode()
将列放回相应的php变量/状态。