简体   繁体   中英

How to get Properties from JSON encoded array in javascript from PHP?

I can't for the life of me get the values out from a JSON encoded array in javascript from PHP?

$company = new stdClass();
$company->PostCode   = $orgs->Organisation[$i]->BookingCategory->BookingDetails->OrganisationPostCode;
$company->Name       = $orgs->Organisation[$i]->OrganisationName;
$company->Address1   = $orgs->Organisation[$i]->BookingCategory->BookingDetails->OrganisationAddress1;
$company->Address2   = $orgs->Organisation[$i]->BookingCategory->BookingDetails->OrganisationAddress2;

array_push($myArr,$company);
$someJSON = json_encode($myArr);
echo $someJSON;

That gives me this which is returned

[{"PostCode":{"0":"mypostcode"},"Name":{"0":"mycomanyname"},"Address1":{"0":"myaddress1"},"Address2":{"0":"myaddress2"}}]

I've tried this and other permutations in xmlhttprequest:

var JSONObject = JSON.parse(this.responseText);
for (var key in JSONObject) {
    postcode = JSONObject[key][0]["PostCode"].PostCode
}

Some code omitted such as the loop etc. Any ideas?

considering your code you have to do

var JSONObject = JSON.parse(this.responseText);
for (var key in JSONObject) {
  postcode = JSONObject[key].PostCode[0];
}

Not sure what the protocol is regarding finding my own answer,so sorry if this is incorrect. I managed to get the values out like this, posting for others:

JSONObject[key]["PostCode"][0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM