Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

php - How to check if a variable even exist after decode JSON?

I have this JSON string.

[
   {
     "name": "user_title",
     "value": "Bapak."
   },
   {
     "name": "user_firstname",
     "value": "Test"
   },
   {
     "name": "user_lastname",
     "value": "XXX"
   }
]

This string generated dynamically. It may has more or less. I use JSON Decode to process it in PHP.

$json_form      = json_decode($json_string,true);

$user_title     = $json_form[0]['value'];
$user_firstname = $json_form[1]['value'];
$user_lastname  = $json_form[2]['value'];

How do I check the variable user_title even exist in the string?

If it exist I should get the value but if not that means $user_title = NULL.

question from:https://stackoverflow.com/questions/65915131/how-to-check-if-a-variable-even-exist-after-decode-json

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You might want to consider mapping your JSON into a key/value array using array_column; then it is easy to check for the existence of a value. For example:

$json_form = json_decode($json_string, true);
$values = array_column($json_form, 'value', 'name');

$user_title     = $values['user_title'];
$user_firstname = $values['user_firstname'];
$user_lastname  = $values['user_lastname'];

echo "title: $user_title
first name: $user_firstname
last name: $user_lastname
";

Output for your sample data is:

title: Bapak.
first name: Test
last name: XXX

It's also easy to add default values when a key is missing, for example:

$user_title     = $values['user_title'] ?? '';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...