下午好,
我目前在使用PHP从json文件获取数据时遇到问题。
我现在得到的是
$jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}', true);
echo ($jsondecoded[0]->chat);
如你所见。我正试图获取聊天信息。但是,当我试图这样做时,它不会回应任何东西。我一直试图弄清楚为什么会这样,但我遗憾地找不到它。我必须遗漏一些东西,但我无法弄清楚我错过了什么。
先谢谢。
答案 0 :(得分:2)
三个错误:
1)在json结束时丢失了。
2)您正在使用json_decode的“array assoc”选项,因此它不会返回对象。
3)您无法回显聊天对象。
试试这个:
$jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]');
echo ($jsondecoded[0]->chat->username);
答案 1 :(得分:0)
$jsondecoded = json_decode('[{"chat": {"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]', true);
此外,请记住,您已使用true
作为json_decode
的第二个参数,这意味着您要将结果转换为关联数组,要么删除true
,要么更改访问:
var_dump($jsondecoded[0]['chat']);
答案 2 :(得分:0)
你的json在json字符串的结尾添加']'结尾时无效,而php中的print数组使用print_r函数。 '[0]'用于获取第一个元素,['chat']用于获取聊天键的值
$jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]', true);
print_r ($jsondecoded[0]['chat']);
输出将
Array
(
[username] => RobloxProtectorKing
[message] => :slender me
[time] => 2018-03-20 01:56:12
)
答案 3 :(得分:-1)
以下是我所拥有的模板的示例。希望它有所帮助。
<?php
/* Status Codes
return 0 = Nothing to Update (n/a)
return 1 = Successful Insert Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */
/* Disable Warnings so that we can return ONLY what we want through echo. */
mysqli_report(MYSQLI_REPORT_STRICT);
// First get raw POST input
$raw_post = file_get_contents('php://input');
// Run through url_decode..
$url_decoded = urldecode($raw_post);
// Run through json_decode...
// false to allow for reference to oject. eg. $column->name instead of $column["name"] in the foreach.
$json_decoded = json_decode($url_decoded, false);
$pk_line_item_id = (strlen($json_decoded[0]->value) > 0 ? $json_decoded[0]->value : null);
// INCLUDE DB CONNECTION STRING
include 'php_pdo_mysql_connect.php';
// SQL INSERT query...
$stmt = $link->prepare(" SELECT * FROM tbl_xyz ");
//$stmt->bindParam(':pk_line_item_id', $pk_line_item_id, PDO::PARAM_INT); // INT
// Execute this SQL statement.
$stmt->execute();
// Fetch & Populate the single returned in var $resultSet.
$resultSet = $stmt->fetchAll();
// Returns an array indexed by column number as returned in your result set, starting at column 0.
// https://www.ibm.com/support/knowledgecenter/en/SSEPGG_9.7.0/com.ibm.swg.im.dbclient.php.doc/doc/t0023505.html
// If the search record was found, populate it on the html table.
if (($resultSet !== false) && ($stmt->rowCount() > 0)) {
// Set JSON headers
header('Content-type:application/json;charset=utf-8');
// Encode entire $resultSet array to JSON.
$json_encoded = json_encode($resultSet);
// Ready to return as JSON to client side JQuery / Java Script...
echo $json_encoded;
}
?>