如何构建PHP数组并转JSON以生成指定格式的JSON字符串
问题描述
需要生成如下格式的JSON字符串:
{ "value": [ "01GQSE92030S8MNA78WQZ09JJQ", "{ \"user_id\": \"{{current_user.id}}\", \"user_phone\": \"{{current_user.phone}}\", \"ticket_id\": \"{{ticket.id}}\", \"ticket_comment\": \"{{ticket.latest_comment}}\", \"ticket_comment_author\": \"{{ticket.latest_comment.author.name}}\", \"organization_id\": \"{{ticket.organization.external_id}}\", \"organization_name\": \"{{ticket.organization.name}}\", \"requester_name\": \"{{ticket.requester.name}}\", \"requester_phone\": \"{{ticket.requester.phone}}\" }" ] }
注意:目标JSON中value数组的第二个元素是转义后的JSON格式字符串,而非原生JSON对象。
你尝试的PHP数组无法得到正确结果,原代码结构错误:
array( "value" => "01GQSE92030S8MNA78WQZ09JJQ", array( "user_id" => "{{current_user.id}}", "user_phone" => "{{current_user.phone}}", "ticket_id" => "{{ticket.id}}", "ticket_comment" => "{{ticket.latest_comment}}", "ticket_comment_author" => "{{ticket.latest_comment.author.name}}", "organization_id" => "{{ticket.organization.external_id}}", "organization_name" => "{{ticket.organization.name}}", "requester_name" => "{{ticket.requester.name}}", "requester_phone" => "{{ticket.requester.phone}}", "agent_external_id" => "{{current_user.external_id}}", "ticket_external_id" => "{{ticket.external_id}}", "customer_external_id" => "{{ticket.requester.external_id}}" ) );
解决方案
要生成目标格式,需注意两个核心点:
value必须是包含两个元素的数组- 第二个元素需是JSON字符串(先把内部键值对转为JSON,再作为字符串存入数组)
正确的PHP代码如下:
// 定义内部需要的键值对数组(仅保留目标JSON要求的字段) $innerData = [ "user_id" => "{{current_user.id}}", "user_phone" => "{{current_user.phone}}", "ticket_id" => "{{ticket.id}}", "ticket_comment" => "{{ticket.latest_comment}}", "ticket_comment_author" => "{{ticket.latest_comment.author.name}}", "organization_id" => "{{ticket.organization.external_id}}", "organization_name" => "{{ticket.organization.name}}", "requester_name" => "{{ticket.requester.name}}", "requester_phone" => "{{ticket.requester.phone}}" ]; // 将内部数组转为JSON字符串(自动处理引号转义) $innerJsonStr = json_encode($innerData); // 构建最终数组结构 $finalArray = [ "value" => [ "01GQSE92030S8MNA78WQZ09JJQ", $innerJsonStr ] ]; // 生成格式化的最终JSON $finalJson = json_encode($finalArray, JSON_PRETTY_PRINT); // 输出结果 echo $finalJson;
代码说明
- 先创建内部键值对数组,剔除你原代码中多余的3个字段,匹配目标JSON的内容
- 用
json_encode($innerData)将数组转为JSON字符串,自动完成引号转义,符合目标格式要求 - 最终数组的
value字段是包含两个元素的数组:第一个是ID字符串,第二个是生成的JSON字符串 - 加上
JSON_PRETTY_PRINT参数可以生成和目标一致的格式化JSON
内容的提问来源于stack exchange,提问作者Megamind
相关产品推荐
相关产品推荐

