0

我想用这个结构创建一个 JSON:

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

我愿意:

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

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

我得到:

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

如何修复它?

更新

我试过这个:

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

但是得到:

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

怎么了?

4

3 回答 3

8

不要以这种方式构建 JSON。改为在 PHP 数组上使用json_encode 。

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

输出

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

要使用您的$ws阵列,您可能可以执行以下操作:

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

注意像这样使用array_map需要>= PHP 5.3

于 2013-10-07T07:16:08.447 回答
1

您需要先创建一个数组,然后使用 json_encode 创建 json 输出。不要在那里硬编码任何json..

于 2013-10-07T07:19:31.767 回答
1

与其在函数中构建 json 字符串,funcArray不如构建一个数组并返回它

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);
于 2013-10-07T07:24:49.463 回答