PHP:为一组 JSON 对象命名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18377469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Give a name to an array of JSON objects?
提问by user1739825
I have managed to get data from database in PHP file. From there(data.php),
我已经设法从 PHP 文件中的数据库中获取数据。从那里(data.php),
$output = json_encode($result);
The result would be like this,
结果会是这样
$output=[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]
So how do I give name "kitten" an array of kitty objects in php format?
那么如何以 php 格式命名“kitten”一组 kitty 对象呢?
For example like
例如像
"kitten":[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]
回答by Brewal
You have to wrap your result in another array on the 'kitten' key :
您必须将结果包装在 'kitten' 键上的另一个数组中:
$output = json_encode(['kitten' => $result]);
回答by Kenny
Try this:
尝试这个:
<?php
$kitty = array('kitten' => array());
$kitty['kitty'][] = array('kitty' => 'Tabby');
$kitty['kitty'][] = array('kitty' => 'Ruby');
$kitty['kitty'][] = array('kitty' => 'Silver');
var_dump($kitty);
var_dump(json_encode($kitty));
which results in: {"kitty":[{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]}
这导致: {"kitty":[{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]}
回答by Bora
Use nested encode
and decode
使用嵌套encode
和decode
$json = '[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]';
echo json_encode(array('kitten' => json_decode($json)));
回答by Meyka Jograt
try to use this
尝试使用这个
$output['kitty'][] = json_encode($result);
回答by d-feverx
$result =array('kitten'=> $output);
output
输出
{
"kitten":[
{"kitty":"Whitely"},
{"kitty":"Tabby"},
{"kitty":"Ruby"},
{"kitty":"Silver"}
]
}