1

I've used the json_encode function in the past to create simply JSON objects like this:

$payload =  array ("user" => $username, "password" => $password, "group" => $group);
$payload = json_encode ($payload);

which creates this:

{"user":"john smith","password":"abc12345","group":"sales"}

I now need to generate a JSON array like this:

{
  "query": [
    {
      "Date": "11/01/2017...12/31/2017"
    }
  ]
}

but I can't find the correct syntax.

1

3 Answers 3

2

You can simply create a 2d array in php.

$payload =  array (
    "query" => array(
         array(
             "date" => "11/01/2017...12/31/2017",
             "other sub key" => "other sub value"
         )
    ),
    "other main key" => array(
         array(
             "other sub key" => "other sub value",
             etc...
         )
    )
);
Sign up to request clarification or add additional context in comments.

4 Comments

This will make query an object but OP wants an array
I'm not sure what you mean, in my code "query" is a key, not an array...
I mean the value of the query property in the resulting JSON. Your code will produce "query":{"date":"11/01/2017...12/31/2017"} (an object value) whereas OP wants "query":[{"Date":"11/01/2017...12/31/2017"}] (an array value)
Ah, I see, I missed and array. I edited my answer so that it fits now.
2

That would be something like this

$array = array(
    'query' => array(
        array('Date' => '11-01-2017')
        )
    );


echo '<pre>';
print_r(json_encode($array, JSON_PRETTY_PRINT));

Result

{
    "query": [
        {
            "Date": "11-01-2017"
        }
    ]
}

Comments

0
$payload = json_encode($payload, JSON_PRETTY_PRINT);

reference: http://php.net/manual/en/function.json-encode.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.