假设我有一个变量$ data ['media']; 问题是数据可能看起来像一个字符串,例如
$data['media'] = '1|BlahBLah2|0'
或者它可能以json编码的字符串形式出现,例如
$data['media'] = '{"site_id":"1","string":"BlahBlah2","cool":"0"}';
区分它是分隔字符串还是json编码字符串的最佳方法是什么?
答案 0 :(得分:0)
json_decode
将返回已解码数据或NULL
,因此您可以使用以下内容:
$decode = json_decode($data['media']);
if ($decode)
{
// the data was json encoded, so now we can process it
$data['media'] = $decode;
}
else // data is a string
答案 1 :(得分:0)
if( json_decode( $data['media'] )!==NULL || strtolower( $data['media'] )=='null' )
{
$data['media'] = json_decode( $data['media'] );
}
else
{
# Not a JSON string
}