<?php declare(strict_types=1); ini_set('display_errors', 'On'); ini_set('error_reporting', E_ALL); function v(mixed $value, mixed ...$values): void { ob_start(); var_dump($value); echo ob_get_clean(); foreach ($values as $v) { v($v); } } /** * Json类 */ class Json { /** * 对变量进行JSON编码 * * @param mixed $value 待编码的value,除了resource类型之外,可以为任何数据类型 * @return string|false 成功则返回JSON编码的string或者在失败时返回false */ public static function encode(mixed $value): string|false { try { $encode = json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } catch (JsonException) { $encode = false; } return $encode; } /** * 对JSON格式的字符串进行解码 * * @param string $json 待解码的json string格式的字符串 * @return mixed 返回编码的数据,若解码失败将会返回null */ public static function decode(string $json): mixed { try { $decode = json_decode($json, true, 512, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } catch (JsonException) { $decode = null; } return $decode; } } $profile = ['name' => '张三', 'sex' => '男', 'birth' => 2003]; $encode = Json::encode($profile); v($encode); // string(42) "{"name":"张三","sex":"男","birth":2003}" $decode = Json::decode($encode); v($decode); // array(3) { ["name"]=> string(6) "张三" ["sex"]=> string(3) "男" ["birth"]=> int(2003) }
Copyright © 2024 码农人生. All Rights Reserved