Create JSON string with php issue -


i want create json structure:

{"id":"ws",  "data":[    {"name":"it.geosolutions"},    {"name":"cite"},    {"name":"testwor"},    {"name":"tiger"},    {"name":"sde"},    {"name":"topp"},    {"name":"newwork"},    {"name":"sf"},    {"name":"nurc"}  ] } 

i do:

function funcarray(){  foreach ($ws $item){   $wsarray[] = '{"name":"'.$item->name.'"}';  }    return $wsarray; }  $json_data = array ('id'=>'ws','data'=>funcarray()); $json = json_encode($json_data); 

and get:

{"id":"ws",  "data":[    "{\"name\":\"it.geosolutions\"}",    "{\"name\":\"cite\"}",    "{\"name\":\"testwor\"}",    "{\"name\":\"tiger\"}",    "{\"name\":\"sde\"}",    "{\"name\":\"topp\"}",    "{\"name\":\"newwork\"}",    "{\"name\":\"sf\"}",    "{\"name\":\"nurc\"}"   ] } 

how repair it?

update

i tried this:

function funcarray(){  foreach ($ws $item){    $wsarray[] = json_encode(array('name'=>$item->name));  }    return $wsarray; } 

but get:

{"id":"ws","data":["{\"name\":\"it.geosolutions\"}","{\"name\":\"cite\"}","{\"name\":\"testwor\"}","{\"name\":\"tiger\"}","{\"name\":\"sde\"}","{\"name\":\"topp\"}","{\"name\":\"newwork\"}","{\"name\":\"sf\"}","{\"name\":\"nurc\"}"]} 

whats wrong?

don't build json way. use json_encode on php array instead.

$arr = array( "id" => "ws", "data" => array(   array("name" => "it.geosolutions"),   array("name" => "cite"),   array("name" => "testwor"),   array("name" => "tiger"),   array("name" => "sde"),   array("name" => "topp"),   array("name" => "newwork"),   array("name" => "sf"),   array("name" => "nurc") ));  echo json_encode($arr); 

output

{"id":"ws","data":[{"name":"it.geosolutions"},{"name":"cite"},{"name":"testwor"},{"name":"tiger"},{"name":"sde"},{"name":"topp"},{"name":"newwork"},{"name":"sf"},{"name":"nurc"}]} 

to work $ws array, can this:

echo json_data(array(   "id" => "ws",   "data" => array_map(function($item) { return array("name" => $item->name); }, $ws) )); 

note using array_map requires >= php 5.3


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -