请求高手解决(怎么把这样的数组转换为JSON) 跪求

lovezx1028 2009-07-08 11:19:54
类似这样的数组怎么把他换输出为JSON的格式:
这样的JOSN格式是不正确的如下:
{"identifier":"id","label":"name","items":[["1","Json"],["2","Bryan"],["3","Andy"],["4","dangany"]]}

下面的是正确:

{"label":"name","identifier":"id","items":[{"id":"1","name":"Json"},{"id":"2","name":"Bryan"},{"id":"3","name":"Andy"},{"id":"4","name":"dangany"}]}


请教-----》》


我的代码如下:
<?php

header("Content-type: text/html; charset=utf-8");
mysql_connect("localhost","root");
mysql_select_db("Json");
mysql_query("set names gb2312");
$sql="select * from A";
$info=mysql_query($sql);
$id=0;
$data=array();
while($Array=mysql_fetch_array($info)){
unset($Array["id"]);unset($Array["name"]);
$data[$id]=$Array;
$id++;
}
$json = array(
"identifier"=>"id",
"label"=>"name",
"items"=>$data,
);


echo json_encode($json);
?>



谢谢。。。。
...全文
125 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
header('Content-type: application/json; charset=utf-8');
HawaiiLeo 2009-07-09
  • 打赏
  • 举报
回复
shagoo写的person类:
class person
{
public $id;
public $name;
}

需要定义一下。
shagoo 2009-07-08
  • 打赏
  • 举报
回复

<?php

header("Content-type: text/html; charset=utf-8");
mysql_connect("localhost","root");
mysql_select_db("Json");
mysql_query("set names gb2312");
$sql="select * from A";
$info=mysql_query($sql);
$id=0;
$data=array();
class Person {} // person class
while($Array=mysql_fetch_array($info)){
//unset($Array["id"]);unset($Array["name"]);
// create person object
$person = new Person();
$person->id = $Array["id"];
$person->name = $Array["name"];
//$data[$id]=$Array;
$data[$id]=$person;
$id++;
}

$json = array(
"identifier"=>"id",
"label"=>"name",
"items"=>$data,
);


echo json_encode($json);
?>
tfxg 2009-07-08
  • 打赏
  • 举报
回复
php5.2以下版本:
require_once('JSON.php');
$cjson = new Services_JSON();

$json = array(
"identifier"=>"id",
"label"=>"name",
"items"=>$data,
);

$output = $cjson->encode($json);
php5.2以上版本
<?php
$json = array(
"identifier"=>"id",
"label"=>"name",
"items"=>$data,
);

echo json_encode($json);
?>
shagoo 2009-07-08
  • 打赏
  • 举报
回复
php5.2以上已经有自带函数了~ http://cn2.php.net/manual/en/function.json-encode.php
低版本的看这里: http://www.luocheng.cn/article-view-190.html
另外你正确的格式中的items段应该是object~
而你的$data却是array~
改一下就可以了~
sun0298 2009-07-08
  • 打赏
  • 举报
回复
路过学习了

20,358

社区成员

发帖
与我相关
我的任务
社区描述
“超文本预处理器”,是在服务器端执行的脚本语言,尤其适用于Web开发并可嵌入HTML中。PHP语法利用了C、Java和Perl,该语言的主要目标是允许web开发人员快速编写动态网页。
phpphpstorm 技术论坛(原bbs)
社区管理员
  • 开源资源社区
  • phpstory
  • xuzuning
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧