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

时间:2022-08-27 18:13:00

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 {
    ...
}

#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 {
    ...
}