Kliver Max
Kliver Max

Reputation: 5299

Create JSON string with php issue

I want to create a JSON with this 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 as $item){
  $wsarray[] = '{"name":"'.$item->name.'"}';
 }  
 return $wsarray;
}

$json_data = array ('id'=>'ws','data'=>funcArray());
$json = json_encode($json_data);

And i get:

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

How to repair it?

UPDATE

I was tried this:

function funcArray(){
 foreach ($ws as $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?

Upvotes: 0

Views: 61

Answers (3)

maček
maček

Reputation: 77806

Don't build JSON this way. Use json_encode on a 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 with your $ws array, you can probably do something like this:

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

Note using array_map like this requires >= PHP 5.3

Upvotes: 8

plain jane
plain jane

Reputation: 1007

Instead of building the json string in the function funcArray why not build an array and return it

function funcArray(){
   foreach ($ws as $item){
       $wsarray[] = array("name"=>$item->name);
    }  
    return $wsarray;
  }

 $json_data = array ('id'=>'ws','data'=>funcArray());
 $json = json_encode($json_data);

Upvotes: 1

Nes
Nes

Reputation: 304

You need to create a array first then use json_encode to create json output. Dont hard code any json there..

Upvotes: 1

Related Questions