[英]How to access variables of nested arrays in PHP
我正在将数据从javascript发送到我的php服务器。 但是我无法访问所有发送的变量。 有一些嵌套的数组和JSON字符串,我只是不知道如何访问它们。
这是我的代码:
$scope.report = {
'title': '',
'desc': '',
'address': {
'text': '',
'lat': '',
'lng': ''
},
'tags': ['none chosen']
};
function postToServer () {
var data = {
'do': 'addNewReportToDatabase',
'data': {
'usr': userId,
'report': JSON.stringify($scope.report)
}
};
$http({
url: $rootScope.server_url,
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
alert(response);
});
}
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$data = json_decode(json_encode($request->data), True);
if (isset($request->do)) {
switch ($request->do) {
case 'addNewReportToDatabase':
$reportStr = $data['report'];
$reportJSON = json_decode($reportStr);
echo $reportJSON['title'];
break;
}
}
我无法访问报告变量的任何变量。
我可以说echo json_encode($reportJSON);
如果我将其记录在JS中,则得到的响应将是一个包含所有变量的对象 !
字符串化版本如下所示: {"title":"title","desc":"describtion","address":{"text":"address","lat":"","lng":""},"tags":["Unfall","Terrorismus","Regional"]}
如果我使用var_dump($reportJSON);
我得到以下输出:
"object(stdClass)#3 (4) { ["title"]=> string(5) "title" ["desc"]=> string(11) "describtion" ["address"]=> object(stdClass)#4 (3) { ["text"]=> string(7) "address" ["lat"]=> string(0) "" ["lng"]=> string(0) "" } ["tags"]=> array(3) { [0]=> string(6) "Unfall" [1]=> string(11) "Terrorismus" [2]=> string(8) "Regional" } } "
那为什么我不能用我的php访问变量呢?
如果要这样访问,则必须在json_decode()
第二个参数设置为true
。
更改为这一行(在server.php中):
$reportJSON = json_decode($reportStr, true); // <-- add second param true
您正在以关联数组而不是对象的形式访问report
。
您的echo $reportJSON['title']
应该insetead:
echo $reportJSON->title;
因为在您的var_dump
, $reportJSON
的类型为: object(stdClass)#3...
就个人而言,我喜欢将JSON数据作为对象使用,这种方式使代码更易于阅读,并且在某些情况下避免出现未定义索引的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.