[英]Fetching data from Json
I have a json object. 我有一个JSON对象。 I need to get the values after decoding the json object.
我需要在解码json对象后获取值。
However, some values are blank at times. 但是,有些值有时为空白。 This brings an error to the way I am fetching.
这给我获取的方式带来了错误。
Kindly see below and advice. 请参阅下面的建议。
$json = '{
"Customers": {
"IdentityStrings": [
{
"UniqueSystemIdentifier": "202000000000007004",
"MSISDN": "211920494162",
"FirstName": "Donald",
"MiddleName": {
},
"LastName": "Twesiga",
"DateOfBirth": "2000-01-01",
"DateIdentityActivated": "20170816153810",
"DateIdentityRegistered": "20170816153448",
"OperatorNameRegisteredBy": {
},
}
]
},
}';
To get the values, I json decode and fetch as below. 为了获取值,我对json进行解码并按以下方式获取。
$jsonData = json_decode($json);
foreach ($jsonData->Customers->IdentityStrings[0] as $key => $value) {
$UniqueSystemIdentifier = ($jsonData->Customers->IdentityStrings[0]->UniqueSystemIdentifier);
$MSISDN = ($jsonData->Customers->IdentityStrings[0]->MSISDN);
$FirstName = ($jsonData->Customers->IdentityStrings[0]->FirstName);
$MiddleName = ($jsonData->Customers->IdentityStrings[0]->MiddleName);
$LastName = $jsonData->Customers->IdentityStrings[0]->LastName;
$DateOfBirth = $jsonData->Customers->IdentityStrings[0]->DateOfBirth;
$OperatorNameRegisteredBy = $jsonData->Customers->IdentityStrings[0]->OperatorNameRegisteredBy;
}
The problem comes when some are empty like in this case MiddleName
and OperatorNameRegisteredBy
. 当某些内容为空时(例如在这种情况下,
MiddleName
和OperatorNameRegisteredBy
,问题就来了。
How can I fetch in case they have values or not? 如果它们具有值,我该如何获取?
Thank you. 谢谢。
Use ternary conditions so that you can get rid of the error; 使用三元条件,以便您可以消除该错误;
$MSISDN = (isset($jsonData->Customers->IdentityStrings[0]->MSISDN) && !empty($jsonData->Customers->IdentityStrings[0]->MSISDN))? $jsonData->Customers->IdentityStrings[0]->MSISDN : "";
So the same for all the values. 所有值都相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.