php is_json()能否檢測(cè)json數(shù)組

PHP
小樊
81
2024-09-11 05:45:26

is_json() 函數(shù)本身不是 PHP 的內(nèi)置函數(shù)。但是,你可以使用以下方法來(lái)檢測(cè)一個(gè)字符串是否是有效的 JSON 數(shù)組:

function is_json_array($string) {
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE) && (json_decode($string, true) !== null);
}

$json_array = '[1, 2, 3]';
if (is_json_array($json_array)) {
    echo "This is a valid JSON array.";
} else {
    echo "This is not a valid JSON array.";
}

這個(gè) is_json_array() 函數(shù)首先嘗試對(duì)輸入的字符串進(jìn)行解碼。如果解碼成功且沒(méi)有錯(cuò)誤,那么它將返回 true,表示這是一個(gè)有效的 JSON 數(shù)組。如果解碼失敗或者解碼后的值為 null,則返回 false,表示這不是一個(gè)有效的 JSON 數(shù)組。

0