dsomm80482 2016-06-27 13:14
浏览 29

有没有办法检查对象中的值是否设置为不使用foreach?

I have the following JSON object:

{
  "screen": 1,
  "parameters": {
    "title": "Fill in the form:",
    "values": [
      {
        "id": 13,
        "type": 2,
        "name": "A",
        "label": "Lorem ipsum",
        "value": 10
      },
      {
        "id": 14,
        "type": 2,
        "name": "B",
        "label": "Lorem ipsum",
        "value": 20
      }
    ]
  }
}

In the code I access the values using $screen = /*object*/; $screen->parameters->values.

Is there a fast way to check if the values of answer A and B are filled in? I tought something like this:

if(isset(A) && isset(B)) { ... }

For those who are interested, I use laravel 5, maybe there is a method for it?

It looks like I need an foreach, but I rather avoid those in this case...

  • 写回答

1条回答 默认 最新

  • dora0817 2016-06-27 13:49
    关注

    Nope, not with the current structure. You could however change the structure a bit to support this. You could use an object instead of an array and use the name as keys:

    {
      "screen": 1,
      "parameters": {
        "title": "Fill in the form:",
        "values": {
          "A":{
            "id": 13,
            "type": 2,
            "label": "Lorem ipsum",
            "value": 10
          },
          "B":{
            "id": 14,
            "type": 2,
            "label": "Lorem ipsum",
            "value": 20
          }
        ]
      }
    }
    

    You could then use your isset method.

    isset( $screen->parameters->values->A );
    

    You can still loop over the values as you can turn this whole thing in an associative array by passing true to json_decode as a second parameter. I for one am not a big fan of my own answer, and would probably just loop the thing, but it may still answer your question.

    edit: I forgot that if you add true to json_decode, you also access your properties like this:

    isset( $screen['parameters']['values']['A'] );
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。