如何在PHP中将指定键值对格式的字符串转换为数组?
在PHP中将JSON字符串转换为数组的方法
你给出的字符串是标准JSON格式,直接用PHP内置的json_decode()函数就能完成转换,具体操作如下:
核心代码示例
// 你的原始JSON字符串 $jsonString = '{"Name?":"Hamz","Why do you want to join the team?":"Test","Your Date of Birth?":"2000-05-02","Your Age?":"25"}'; // 转换为关联数组(第二个参数设为true) $resultArray = json_decode($jsonString, true); // 打印数组查看结果 print_r($resultArray);
执行后会得到如下关联数组:
Array ( [Name?] => Hamz [Why do you want to join the team?] => Test [Your Date of Birth?] => 2000-05-02 [Your Age?] => 25 )
关键说明
json_decode()的第二个参数设为true时,会将JSON对象转换为PHP的关联数组;如果省略该参数或设为false,会转换为stdClass对象。- 如果转换失败(比如JSON格式有误),可以用
json_last_error()和json_last_error_msg()排查问题:$resultArray = json_decode($jsonString, true); if (json_last_error() !== JSON_ERROR_NONE) { echo '解析失败:' . json_last_error_msg(); }
内容的提问来源于stack exchange,提问作者Hamz
相关产品推荐
相关产品推荐

