首页 > 解决方案 > json_decode 显示没有数据

问题描述

我正在使用以下逻辑使用 PHP 在 MySQL 中以 JSON 格式存储数据。

foreach ($_POST['data'] as $key => $value)
    {
        if($value[1] == "page_keywords")
            $store .= json_encode(array($value[1] => $value[2]));
        else
            $store .= json_encode(array($value[1] => trim($value[2])));
    }

session_start();
$date = new Date();
$modified = $date->getDate();

$query = ' UPDATE pages SET last_updated_user_author_id = "'.$_SESSION['user_id'].'", data = "'.htmlentities($store, ENT_QUOTES).'", modified = "'.$modified.'" WHERE id = "'.$pageID.'" ';

然后在解码数据时我使用以下逻辑:

$query = ' SELECT data FROM pages WHERE id = "'.$_POST['pageID'].'" ';
$connection = $this->establish_connection();
$data = $connection->query($query);
$connection->close();
if($data->num_rows > 0)
    {
        while($row = $data->fetch_assoc())
            {
                $var = html_entity_decode($row['data']);
                echo json_decode($var);
            }
    }

虽然 json_decode 它没有显示任何数据作为响应,但当我执行 var_dump 时它显示 null,但是如果我没有执行 json_decode 并且只使用了 html_entity_decode() 我得到低于输出

{"page_base_url":"http://www.myblog.com/about/contact/"}{"page_url_revision":"http://www.myblog.com/about/contact/"}{"page_url_alternate":"http://www.myblog.com/about/contact/"}{"page_url_shortlink":"http://www.myblog.com/about/contact/"}{"page_url_canonical":"http://www.myblog.com/about/contact/"}{"page_title":"Example | Contact"}{"page_name":"Example Contact"}{"page_type":"WebSite"}{"page_meta_description":"Want to get in touch with us? You're on the correct page, you can get in touch with us by filling the form below. We will get in touch with you with 24 hours."}{"page_keywords":["example","contact","support","help","getintouch","feedback","bug","updates"]}

我不确定我要去哪里错了,有人可以在这里帮助我吗?

我想给出一个 json_encode 格式的 eccho 作为对 ajax 调用的响应。我使用下面的逻辑这样做

echo json_encode(
                array(
                        "type" => "error",
                        "status" => "Error While Retrieving Data!",
                        "message" => $error
                     )
            );

标签: phpjson

解决方案


我认为你需要类似的东西:

$store = array();
foreach ($_POST['data'] as $key => $value)
    {
        if($value[1] == "page_keywords")
            $store[] = array($value[1] => $value[2]);
        else
            $store[] = array($value[1] => trim($value[2]));
    }

$save = json_encode($store);

甚至(如果您的 $value[1] 在循环中始终是唯一的)

$store = array();
foreach ($_POST['data'] as $key => $value)
    {
        if($value[1] == "page_keywords")
            $store[$value[1]] = $value[2];
        else
            $store[$value[1]] = trim($value[2]);
    }

$save = json_encode($store);

然后使用 $save 存储在您的表中。不过,我不是 100% 的。


推荐阅读