我想用这种结构创建一个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\"}"]}
怎么了?
答案 0 :(得分: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
答案 1 :(得分:1)
您需要先创建一个数组,然后使用json_encode创建json输出。不要硬编码任何json ..
答案 2 :(得分:1)
不是在函数funcArray
中构建json字符串,而是为什么不构建数组并将其返回
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);