如何访问PHP中嵌套数组的变量

How to access variables of nested arrays in PHP

本文关键字:嵌套 数组 变量 PHP 何访问 访问      更新时间:2023-12-19

我正在将数据从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