I have the following structure in JSON:
[
{
"id":"79",
"value":"val1"
},
{
"id":"88",
"value":["val1","val2","new"]
}
]
How to handle this cases? I've tried this but it only handle the first case:
<?php
$arr = json_decode($json_string);
$itemsList = new stdClass;
$i_d=0;
foreach ($arr as $key=>$arrj):
$itemsList->id[$i_d] = $arrj->id;
$itemsList->value[$i_d] = $arrj->value;
$i_d++;
endforeach;
?>
Thanks in advance.
Inside your foreach loop, you can check that $arrj->value
is an array. If it is, you can loop over it and add its values into your result object one by one, and if it isn't, you can add the single value as you already are.
<?php
$arr = json_decode($json_string);
$itemsList = new stdClass;
foreach ($arr as $key=>$arrj):
$itemsList->id[] = $arrj->id;
if (is_array($arrj->value)) { // Is it an array?
foreach ($arrj->value as $value) { // If so, add its values in a loop
$itemsList->value[] = $value;
}
} else {
$itemsList->value[] = $arrj->value; // if not, just add the single value
}
endforeach;
?>
I removed the $i_d
variable; it is unnecessary because PHP will automatically create numeric indices beginning with 0 when you add values to an array using []
.