我有一个看起来像这样的函数。
function startChatSession($items) {
foreach ($test as $chatbox => $void) {
$items .= $this->chatBoxSession($chatbox);
}
if ($items != '') {
$items = substr($items, 0, -1);
}
header('Content-type: application/json');
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
exit(0);
}
我对这个函数的第二部分很感兴趣。我想把它翻译成类似的东西:
echo json_encode(array(
'username'=>$_SESSION['username'],
'items'=>$items
));
exit;
这种作品,但不完全是。
响应应该是这样的:
{
"username": "johndoe",
"items": [{
"s": "1",
"f": "janedoe",
"m": "dqwdqwd"
}, {
"s": "1",
"f": "janedoe",
"m": "sdfwsdfgdfwfwe"
}, {
"s": "1",
"f": "janedoe",
"m": "werwefgwefwefwefweg"
}]
}
在我的例子中它看起来像:
{
"username": "johndoe",
"items": "\t\t\t\t\t {\r\n\t\t\t\"s\": \"1\",\r\n\t\t\t\"f\": \"babydoe\",\r\n\t\t\t\"m\": \"test\"\r\n\t },\t\t\t\t\t {\r\n\t\t\t\"s\": \"1\",\r\n\t\t\t\"f\": \"\",\r\n\t\t\t\"m\": \"\"\r\n\t }"
}
有什么想法吗?
谢谢
编辑:
如果我将 $items
转储成如下内容:
{
s: 1,
f: babydoe,
m: test
}, {
s: 1,
f: babydoe,
m: test
}, {
s:1,
f: babydoe,
m: test
}, {
s: 1,
f: babydoe,
m: test
}
最佳答案
试试这个:
echo json_encode(array(
'username'=>$_SESSION['username'],
'items'=>array($items)
));
你需要一个多级数组。
参见 codepad例如。
关于php - 如何在 php 中构建一个 json 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11164124/