你对JSON有点新意,所以请忍受我的愚蠢......我正在开发一个聊天应用程序,我试图在我的工作PHP脚本上使用json ..我已经尝试过了远在我执行数据库查询后,我将结果编码为JSON然后我使用json_decode
然后将其插入我的foreach语句
这是包含json_encode
和json_decode
的PHP代码
<?php
session_start();
$username=$_SESSION['username'];
$user_id = $_SESSION['id'];
require "config.php";
$con = new PDO("mysql:host=".db_host.";dbname=chat_db",db_username,db_password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="SELECT id,firstname,lastname,status,flag,flag2 FROM users WHERE id != :uid";
$stmt=$con->prepare($sql);
$stmt->bindValue("uid", $user_id, PDO::PARAM_STR);
$stmt->execute();
$sql2="UPDATE users SET status= 1 WHERE status = 0 AND id = :uid";
$stmt2=$con->prepare($sql2);
$stmt2->bindValue("uid", $user_id, PDO::PARAM_STR);
$stmt2->execute();
$rows =$stmt->fetchAll();
$str = json_encode($rows);
$str2 = json_decode($str);
foreach($str2 as $row){
$uid = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$sts = $row['status'];
$flg = $row['flag'];
$flg2 = $row['flag2'];
?>
<li>
<a href="#" data-usernem="<?php echo $username; ?>" data-suid="<?php echo $user_id; ?>" data-userid="<?php echo $uid; ?>" data-role="button"><?php echo $firstname . PHP_EOL . $lastname; ?> </a>
<span class="typing-stats idle" data-type-status="<?php echo $flg2; ?>"> Typing... </span>
<span class="mail msg" data-flag="<?php echo $flg; ?>"> <a href="#" data-role="button"><i class="fa fa-envelope-o"></i></a> </span>
<span class="bullet" data-status="<?php echo $sts; ?>"> </span>
</li>
<?php
}
?>
如果此脚本执行,则会给我一个错误Fatal error: Cannot use object of type stdClass as array in D:\site_deploy\chat\includes\loadusers.php on line 22
我正确使用json_encode
和json_decode
吗?
我很确定我在json_decode
我试过var_dump它,它给了我编码的数据集FYI
答案 0 :(得分:1)
使用参数true
将其转换为数组。
$str2 = json_decode($str, true);