Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make arrays/json appear in the correct way

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading