dqkyz02602 2013-09-04 19:48
浏览 7

在PHP中解析解码的JSON

I have managed to decode some JSON in PHP successfully (not as painful as I thought), but it's been such a long time since I've done any real PHP, my brain has drawn a blank on the following.

The decoded json looks like this

[Array]
item {
      [0]
      {
         [live]=>
         [name]=>Paul
         [value]=>10
      }
      [1]
      {
         [live]=>1
         [name]=>Fred
         [value]=>32
      }

and so on

The problem I'm having is this - I'm trying to iterate through the structure to test first if live==1 and then if it's the first live name, to output it as a selected value to a HTML drop down.

I'm currently trying like this

$t = 0;
$count = 0;
foreach($decode['items'] as $option=>$value)
{
print_r("option = $option
");
    if ($option=>isLive == 1)   
{
    print_r("isLive is true for $option[$count]['names']
");
        if ($t == 0)
        {
        echo "<option value=$option[name] selected>$value[name]</option>";
        $t = 1;
    }
    else
        echo "<option value=$option[name]>$value[name]</option>";
    }  
    else 
    {
    print_r("isLive is false for $option[$count]=>name
");
    }
    $count++;
}

the problem is that I don't seem to be able to get the if statement correct for this to work. This is probably a seriously simple problem and will no doubt make me face palm, but I could do with a pointer in the right direction here!

  • 写回答

2条回答 默认 最新

  • dongqiangteng7319 2013-09-04 19:54
    关注

    If the json is like you showed us you could not iterate over anything with your foreach because your array does not contain a key named items.

    Using the provided structure this should do the trick:

    foreach($decode["item"] as $item) {
        if($item->live == 1) {
            ...
        } else {
            ...
        }
    }
    

    If $item is not an object use $item['live'] instead.

    P.S.: You should really turn error_reporting on. $option=>isLive is no valid syntax.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法