如何访问PHP中嵌套数组的变量
How to access variables of nested arrays in PHP
我正在将数据从javascript发送到我的php服务器。但我无法访问发送的所有变量。有一些嵌套数组和JSON字符串,我就是不知道如何访问它们。
这是我的代码:
sender.js
$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);
});
}
服务器.php
$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访问变量呢??
您正在将report
作为Association数组而不是对象进行访问。
你的echo $reportJSON['title']
应该是固定的:
echo $reportJSON->title;
因为在您的var_dump
中,$reportJSON
的类型为:object(stdClass)#3...
。
就我个人而言,我喜欢将JSON数据作为对象处理,这有点让代码更容易阅读,并在某些情况下避免了未定义索引的注意事项。
如果您想这样访问,则必须在json_decode()
处将第二个参数设置为true
。
更改为此行(在server.php中):
$reportJSON = json_decode($reportStr, true); // <-- add second param true
相关文章:
- 从多维嵌套json数组创建下拉列表
- 如何通过json对象数组为嵌套对象赋值
- 为循环嵌套的Javascript未按预期返回数组
- 具有嵌套对象数组的 Javascript 对象的递归搜索函数
- 将js对象更改为使用嵌套的可观察数组敲除js视图模型
- MongoDB嵌套对象数组后查询
- 从对象数组中动态创建嵌套json
- 使用Angular.js解析JSON中的嵌套对象数组
- 如何将id数组与带下划线的对象数组嵌套属性进行比较
- 将JS对象数组转换为嵌套形式的最有效方法
- 在javascript/angular中创建播放列表(按值复制数组,但按引用设置嵌套对象)
- 嵌套在 ng 重复中的拼接数组
- 嵌套/同心组和mouseenter/mouseleve
- javascript获取嵌套子数组中的对象
- 嵌套捕获组结果
- 如何在嵌套级别不受限制的情况下显示对象的动态嵌套子数组对象
- 按嵌套子数组对 arr 进行排序
- 播放框架 - 表单不绑定到嵌套元组
- 遍历嵌套到组和节中的一组输入
- 在数组和嵌套子数组中搜索Lodash属性