So I have tried to fix this issue myself by looking around. But I don’t seem to be able to figure out how to make my encoded json appear correctly.
This is my code that produces the json:
//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;
When I encode these arrays with json. I get this output:
{
"model": "gpt-model",
"messages": [
{
"role": "user",
"content": "this is my content for user"
}
],
"temperature": 1.15
}
Firstly it completely ignores the 2nd of each $message["role"] and $message["content"]
Secondly I would like the results to get shown exactly like this:
{
"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
}
I want to understand how I can do this and fix a problem like this in the future. I guess that the identical names cause an issue. I know that in PHP the latest variable will be the one that is used.
So how can I solve this?
>Solution :
You need to assign to $messages[] for each nested array. Otherwise you’re only pushing the last value of $message to $messages.
$messages = array();
$message = array();
$message["role"] = "system";
$message["content"] = "this is my content for system";
$messages[] = $message;
$message["role"] = "user";
$message["content"] = "this is my content for user";
$messages[] = $message;