PHP format for JSON

The JSON format that I get is:

{
    "test":[
        {"key1":"value1"},
        {"key2":"value2"}
     ]
}

But is it possible to get this format?

{
    "test": {
        "key1":"value1",
        "key2":"value2"
    }
}

My php code is this:

$key=$row[1];
$value=$row[2];
$posts[] = array($key => $value);

$response['strings'] = $posts;
fwrite($out, json_Encode($response))

I'm stuck on this for hours, someone please help! Thanks in advance!

0
source share
3 answers

Do you want to

$posts[$key] = $value;

The problem is that PHP arrays with string keys are objects in JSON terms.

+2
source

the first is an array, the second is an object.

$posts = new stdClass();
$posts->key1 = "value1";
$posts->key2 = "value2";

$response['strings'] = $posts;
fwrite($out, json_Encode($response))
+1
source

I assume your code is as follows:

$posts = array();
while( somthing )
{
  $row = ...

  $key=$row[1];
  $value=$row[2];
  $posts[] = array($key => $value);
}

$response['strings'] = $posts;
fwrite($out, json_Encode($response))

Your fix:

$posts = array();
while( somthing )
{
  $row = ...

  $key=$row[1];
  $value=$row[2];
  $posts[$key] = $value;
}

$response['strings'] = $posts;
fwrite($out, json_Encode($response))
+1
source

All Articles