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

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大