Reputation: 27048
i have a function that looks like this.
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);
}
i am interested in the second part of this function. I would like to translate it to sometihng like:
echo json_encode(array(
'username'=>$_SESSION['username'],
'items'=>$items
));
exit;
this kind of works, but not quite.
the response should look like:
{
"username": "johndoe",
"items": [{
"s": "1",
"f": "janedoe",
"m": "dqwdqwd"
}, {
"s": "1",
"f": "janedoe",
"m": "sdfwsdfgdfwfwe"
}, {
"s": "1",
"f": "janedoe",
"m": "werwefgwefwefwefweg"
}]
}
in my case it looks like:
{
"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 }"
}
any ideas?
thanks
edit:
if i dump the $items
i the something like:
{
s: 1,
f: babydoe,
m: test
}, {
s: 1,
f: babydoe,
m: test
}, {
s:1,
f: babydoe,
m: test
}, {
s: 1,
f: babydoe,
m: test
}
Upvotes: 4
Views: 669
Reputation: 6601
Change
$items = substr($items, 0, -1);
To:
foreach($items as $index => $d){
$items[$index] = substr($d, 0, -1);
}
Upvotes: 0
Reputation: 6601
Try this:
echo json_encode(array(
'username'=>$_SESSION['username'],
'items'=>array($items)
));
You need a multi level array.
See codepad for example.
Upvotes: 1
Reputation: 13630
Your $items array should look like this:
<?php
$items = array(
0 => array('s'=>1, 'f'=>'janedoe', 'm'=>'dqwdqwd'),
1 => array('s'=>1, 'f'=>'janedoe', 'm'=>'sdfwsdfgdfwfwe'),
2 => array('s'=>1, 'f'=>'janedoe', 'm'=>'werwefgwefwefwefweg')
);
echo json_encode(array(
'username'=>$_SESSION['username'],
'items'=>$items
));
?>
Upvotes: 1