How to build json return in php?

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, for example:

  echo json_encode(array( 'username'=>$_SESSION['username'], 'items'=>$items )); exit; 

this type of work, but not quite.

The answer should look like this:

 { "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 this:

 { "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 reset $items i'm 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 } 
+4
source share
3 answers

Try the following:

  echo json_encode(array( 'username'=>$_SESSION['username'], 'items'=>array($items) )); 

You need a tiered array.

See codepad , for example.

+1
source

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 )); ?> 

http://codepad.org/mZk4hsKq

+1
source

Edit

 $items = substr($items, 0, -1); 

To:

 foreach($items as $index => $d){ $items[$index] = substr($d, 0, -1); } 
0
source

All Articles