[英]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.