0

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?

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Clever use of array_map, +1.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.