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

[英]How to detect whether a JSON object is a String or an Array in PHP? [duplicate]


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循环处理它,所以:

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?

那么检测这个的有效方法是什么?

1 个解决方案

#1


2  

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

您可以使用is_array函数检查var值是否为数组:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2016/12/12/54cedd38e81fd850cff05b896c31a1a.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告