0

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.

Rene Limon
  • 614
  • 4
  • 16
  • 34
  • I'm trying to handle when value atrribute has only simple value and the case when has a array as value – Rene Limon Aug 15 '16 at 19:36
  • Rene, please explain more precisely what you mean by "handle". Your code does handle any type of value; it is simply stored in `$itemsList->value[$i_d]`. What exactly are you trying to achieve? – Matthias Wiehl Aug 15 '16 at 19:43
  • Use the property's type as a condition [in an `if` statement or other conditional statement]. See this: http://stackoverflow.com/questions/4775722/check-if-object-is-array – Tibrogargan Aug 15 '16 at 22:07

1 Answers1

0

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 [].

Don't Panic
  • 41,125
  • 10
  • 61
  • 80