Json response from 3rd party platform which I cant control.
$json = '{
"question1": "answera",
"question2": [
"answerb",
"answerc"]
}';
Any 'question' can have multiple 'answers', however if there is only one 'answer' for that question the response comes back without the [] parentheses - this is breaking the insert into the next system (that I also dont have control over) as it is expecting the [].
Using PHP is there a way to manipulate the json string to be the following, irrelevant of the number of 'answers':
"question1": ["answera"],
CodePudding user response:
You can convert string contents into an array. But you habe to iterate over all answers for this purpose.
Creating an array with an if-condition
<?php
$json = '{
"question1": "answera",
"question2": [
"answerb",
"answerc"
]
}';
// second parameter for array result
$array = json_decode($json, true);
foreach ($array as $question => $answer) {
if (is_string($answer) === true) {
$array[$question] = [ $answer ];
}
}
This one results into ...
array(2) {
'question1' =>
array(1) {
[0] =>
string(7) "answera"
}
'question2' =>
array(2) {
[0] =>
string(7) "answerb"
[1] =>
string(7) "answerc"
}
}
For any further JSON processing you can convert the PHP array back into JSON.
$json = json_encode($array);
Results into ...
string(109) "{
"question1": [
"answera"
],
"question2": [
"answerb",
"answerc"
]
}"
Casting with (array)
Another solution taken from the comments was mentioned by @RickN. Casting with (array)
avoids the if condition and could possibly be faster, if that matters for your application.
foreach ($array as $question => $answer) {
$array[$question] = (array) $answer;
}