dtbrd80422 2016-08-15 19:15
浏览 38
已采纳

如何在PHP中使用JSON处理同一属性的单个项目和数组?

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.

  • 写回答

1条回答 默认 最新

  • duanbodai5166 2016-08-15 20:02
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳