我需要以下面的JSON格式输出数据。
输出:
[
{
"name": "jake",
"age": "20"
}
]
在下面的代码中,我需要设置键和值对,它将提供上述JSON输出。我怎么能这样做?
代码:
$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 );
答案 0 :(得分:1)
您可以使用array_combine
$result = array_combine($key, $value);
结果:
var_dump($result);
array(2) {
["name"]=>
string(4) "jake"
["age"]=>
string(2) "20"
}
var_dump(json_encode($result));
string(26) "{"name":"jake","age":"20"}"
答案 1 :(得分: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"}
答案 2 :(得分:0)
$result = array();
$key = array("name", "age");
$value = array("jake", "20");
$result[] = array_combine($key, $value);
echo json_encode($result);