【问题标题】:How to decode a row from mysql database and encode it如何从mysql数据库中解码一行并对其进行编码
【发布时间】:2019-10-04 08:48:45
【问题描述】:

我正在尝试对行选项进行 JSON 解码,并使用其余数据对其进行编码。但它只给了我选项行但是。如果我不解码它,请在选项行中用反斜杠给我这个。

[{"ID":"4","AppID":"1","Question":"test2","Type":"Radios","OrderNumber":"2","Options":" {\“1号\”: \"Yes\", \"Number2\": \"No\"}"}]

//open connection to mysql db

$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbdata) or die("Error " . mysqli_error($connection));

//fetch table rows from mysql db

$sql = "select * from App_Questions";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

//create an array
$emparray = array();
while ($row =mysqli_fetch_assoc($result)) {
    if ($row["Options"]){
        $str = json_decode($row["Options"]);
        $emparray = $str;
    }else{
        $emparray[] = $row;
    }
}
echo json_encode($emparray);

【问题讨论】:

  • If I don't decode,你为什么不解码 JSON 字符串?数据库中有什么,你有什么,你想要什么? ...以后可能会问,如果数据被转义存储,你是如何写入数据的?
  • 你当前代码的输出是什么?

标签: php mysql arrays json mysqli


【解决方案1】:

假设您想解码保存了 json 数据的字段“选项”,然后您想用其他字段对这些 json 数据进行编码。 json 解码输出来自我们的问题:

array (
  0 => 
  array (
    'ID' => '4',
    'AppID' => '1',
    'Question' => 'test2',
    'Type' => 'Radios',
    'OrderNumber' => '2',
    'Options' => '{"Number1": "Yes", "Number2": "No"}',
  ),
)

如果你解码“选项”,你会得到:

array (
  'Number1' => 'Yes',
  'Number2' => 'No',
)

您可以执行以下操作以使用循环内的其余数据对其进行编码:

    $decodedData = json_decode($results);
    foreach ($decodedData as $row) {
        if (isset($row->Options)) {
            $decodedOptions = json_decode($row->Options);
            foreach ($decodedOptions as $key => $value) {
                $row->$key = $value;
            }
        }
    }
    $decodedData = json_encode($decodedData);
    print_r($decodedData);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2017-06-01
    相关资源
    最近更新 更多