JSON到PHP:获取Object中的Object Array数据

时间:2015-09-22 08:29:51

标签: javascript php jquery arrays json

我有两个JavaScript类:

id_selected = event.GetId()
obj = event.GetEventObject()
print "Label returned:", obj.MenuItems[id_selected].GetLabel()     

下面的Chart类包含上面的Sensor类的Array,一些变量和timeSpan类:

function Sensor(sensorNumber, name, m, b, selected) {
    "use strict";
    this.sensorNumber = sensorNumber;
    this.name = name;
    this.m = m;
    this.b = b;
    this.selected = selected;
}

我通过Jquery AJAX将“chart”对象变量发送给PHP:

function Chart(index, allsensors) {
    "use strict";
    this.chartName = $("#newChartName").val();
    this.chartNumber = index;
    this.sensorsArray = allsensors;
    this.time = new TimeSpan();
}

PHP接收它,这就是我被困住的地方。我需要为传感器对象数组中的每个元素获取“this.Selected”。

function obtainChartData(chart) {
    "use strict";
    $.ajax({
        url: 'server/ExtractTelemetry.php',
        type: "POST",
        data: JSON.stringify(chart),
        success: function (msg) {
            alert(msg);
        }
    });
}

更新:

这是PHP错误输出

enter image description here

JSON输出(缩短但应该是足够的信息):

<?php
    $json = file_get_contents('php://input');
    $chart = json_decode($json);
    echo $startTime = $chart->time->startSec." "; //CORRECT
    echo $endTime = $chart->time->endSec." "; //CORRECT
    echo $chartName = $chart->chartName." "; //CORRECT
    echo $chartNumber = $chart->chartNumber." "; //CORRECT

    for(...) {
    echo $allSensors = $chart->allSensors[someIndexValue]->selected; //why does this not work??
    }
?>

1 个答案:

答案 0 :(得分:3)

json_decode返回一个stdObject。

可以访问该对象的属性

$myObject = json_decode($myString);

$myObject->myProperty;

如果你想从json_decode返回的数组传递一个secnond参数'true'

$myArray = json_decode($myString, true);