2

Possible Duplicate:
PHP : Create array for JSON

I need to output data in the following JSON format.

Output :

[
    {
        "name": "jake",
        "age": "20"

}
]

In the following code, i need to set the key and value pairs in a way where it will give the above JSON output. How could i do this ?

Code :

$result = array();
$key = array("name", "age");
$value = array("jake", "20");

while($i>2)
{
    $result [] = HERE I NEED TO SET <key : value> COMBINATION, I NEED IT TO SET IN A WAY IT WILL GIVE THE FORMAT OF THE JSON OUTPUT GIVEN ABOVE.
}


echo json_encode($result );
Community
  • 1
  • 1
Illep
  • 16,375
  • 46
  • 171
  • 302

3 Answers3

1

You can use array_combine

$result = array_combine($key, $value);

Results:

var_dump($result);

array(2) {
  ["name"]=>
  string(4) "jake"
  ["age"]=>
  string(2) "20"
}

var_dump(json_encode($result));

string(26) "{"name":"jake","age":"20"}"
hsz
  • 148,279
  • 62
  • 259
  • 315
1
$key = array("name", "age");
$value = array("jake", "20");
$json=array();
for($i=0;$i<=count($key)-1;$i++)
{
    $json[$key[$i]]=$value[$i];
}
echo json_encode($json); // {"name":"jake","age":"20"}
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

Try array_combile.

$result = array();
$key = array("name", "age");
$value = array("jake", "20");

$result[] = array_combine($key, $value);

echo json_encode($result);
xdazz
  • 158,678
  • 38
  • 247
  • 274