You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PHP生成的JSON/数组呈现正确格式?

PHP生成多元素JSON数组的正确写法

问题描述

现有PHP代码生成JSON时遇到两个问题:

  • 代码中定义的两组role和content仅保留最后一组值
  • 无法生成包含多个消息对象的messages数组结构

错误代码

//Define messages
$messages = array();
$message = array();
$message["role"] = "system";
$message["content"] = "this is my content for system";
$message["role"] = "user";
$message["content"] = "this is my content for user";
$messages[] = $message;

// Define data
$data["model"] = "gpt-model";
$data = array();
$data["messages"] = $messages;
$data["temperature"] = 1.15;

当前错误输出

{
  "model": "gpt-model",
  "messages": [
    {
        "role": "user",
        "content": "this is my content for user"
    }
 ],
 "temperature": 1.15
 }

期望的JSON结构

{
  "model": "gpt-model",
  "messages": [
    {
      "role": "system",
      "content": "this is my content for system"
    },
    {
      "role": "user",
      "content": "this is my content for user"
    }
  ],
  "temperature": 1.15
}

解决方法

核心原因

PHP数组中同名键会被后续赋值覆盖,你之前的代码是在同一个$message数组里重复赋值role和content,自然只会保留最后一次的值。同时,你只把这个被覆盖后的数组添加到了$messages一次,所以最终只有一个消息对象。

修正后的分步写法

为每个消息创建独立数组,再依次加入$messages:

// 初始化存放消息的数组
$messages = array();

// 创建system消息并加入数组
$message = array();
$message["role"] = "system";
$message["content"] = "this is my content for system";
$messages[] = $message;

// 创建user消息并加入数组(重新初始化$message或用新变量均可)
$message = array();
$message["role"] = "user";
$message["content"] = "this is my content for user";
$messages[] = $message;

// 构建最终数据结构
$data = array();
$data["model"] = "gpt-model";
$data["messages"] = $messages;
$data["temperature"] = 1.15;

// 生成格式化的JSON
echo json_encode($data, JSON_PRETTY_PRINT);

更简洁的字面量写法(推荐)

直接用数组字面量一次性构建完整结构,代码更直观:

$data = array(
    "model" => "gpt-model",
    "messages" => array(
        array(
            "role" => "system",
            "content" => "this is my content for system"
        ),
        array(
            "role" => "user",
            "content" => "this is my content for user"
        )
    ),
    "temperature" => 1.15
);

echo json_encode($data, JSON_PRETTY_PRINT);

通用解决思路

当需要生成包含多个对象的JSON数组时:

  • 每个JSON对象对应一个独立的PHP数组,避免在同一数组内重复赋值同名键
  • 将每个独立数组依次添加到外层数组中
  • 最后使用json_encode()转换为JSON字符串,添加JSON_PRETTY_PRINT可生成格式化输出

内容的提问来源于stack exchange,提问作者Niels Hermann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:15:39