簡體   English   中英

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

這會給每個帶來錯誤,並輸出數組(不可用),如下所示:

[{"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對象表示法的字符串( 讀取:string,而非array )中加載變量。

為了更加清楚:

  • 使用json_encode()在mysql中插入數據。
  • 使用json_decode()將一列放回相應的php變量/狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM