如何在PHP中检测JSON对象是String还是数组? [重复]

如何在PHP中检测JSON对象是String还是数组?  [重复]

问题描述:

This question already has an answer here:

When I have an input like below...

{  
     "number":[  
        "+39XXXXXXXX",
        "+34XXXXXXXX",
        "+49XXXXXXXX"
     ],
     "message":"Sample msg..."
}

I handle it with a foreach loop—like so:

foreach ($message->number as $key => $number) {
    ...                                     
}

However when I have an input like this:

{  
     "number": "+49XXXXXXXX",
     "message": "Sample msg..."
}

I receive an error, cause there is no array to be looped inside the object.

So what is a good and efficient way to detect for this?

</div>

此问题已经存在 这里有一个答案: p>

  • 如何检查变量是否为数组?...或类似数组的内容 6 answers span> li> ul> div>

    当我有一个 输入如下... p>

      {
    “number”:[
    “+ 39XXXXXXXX”,
    “+ 34XXXXXXXX”,
    “+ 49XXX​​XXXXX”
      ],
    “消息”:“示例消息...”
    } 
      code>  pre> 
     
     

    我使用 foreach code>循环处理它 - 像这样: p>

      foreach($ message-&gt; number as $ key =&gt; $ number){
     ... 
    } 
      code>  
     
     

    但是当我有一个输入时 这个: p>

      {
    “number”:“+ 49XXX​​XXXXX”,
    “message”:“Sample msg ...”
    } 
      code>   pre> 
     
     

    我收到一个错误,因为没有数组在对象内循环。 p>

    那么什么是好的有效方式 检测到这个? strong> p> div>

You can check if the var value is array using the is_array function:

if (is_array($message->number) {
    foreach ($message->number as $key => $number) {
        ...                                     
    }
} else {
    ...
}