谁还没个明天 2012-08-02 15:31 采纳率: 66.7%
浏览 9

导航返回的对象

In PHP I have a multidimensional object created from looping through a list of ids

 $summary = array();
 foreach ( $request->id as $id ) {
 ...
 $summary[] = $summary_data;
 }

it's then passed to my javascript.

 return json_encode(array('summary' => $summary));

Not sure how to navigate the returned object correctly. Do I have to use the original list of id's, and use that as an index against this object? Or is there a better way to keep track of this?

End result, I want a select box such that when a new item is selected, its data is displayed.

  • 写回答

1条回答 默认 最新

  • 10.24 2012-08-02 15:41
    关注

    A general JSON object would look like this (trying to put all possible cases):

    {
        "key1":"value1", 
        "subObject":{
            "subKey1":"subValue1",
            "subKey2":"subValue2"
        },
        "arrayOfSubObjects":[
            {"subKey3":"subValue3"},
            {"subKey4":"subValue4"}
        ]
    }
    

    You can reference any element of a JSON object with jsonObject.key, but remember those part between [] are arrays so you'll need to index them as if they were in an array so:

    // to point subKey1:
    
    jsonObject.subObject.subKey1;
    
    // to point subKey3
    
    jsonObject.arrayOfSubObjects[0].subKey3;
    
    OR
    
    // to point subKey1:
    
    jsonObject["subObject"]["subKey1"];
    
    // to point subKey3
    
    jsonObject["arrayOfSubObjects"][0]["subKey3"];
    

    note the 0 has no quotes because it's an index.

    评论

报告相同问题?