php ios utf8编码,PHP / IOS:为网络服务编码json的最佳方法是什么?

我正在尝试创建一个Web服务,通​​过php从mysql数据库提供json,以便在iPhone应用程序中显示.

我有一个标准的mysql / php设置.

数据位于包含字段和记录的表中.用sql查询创建记录集.记录集中的每条记录都是一行.

php

$sql = "SELECT userid,task,longtask FROM tasks WHERE userid = 1 LIMIT 1";

$res = mysql_query($sql) or die(mysql_error());

$tasks = array();

while($row = mysql_fetch_assoc($res)) {

$tasks[] = array('row'=>$row);

}

echo json_encode(array('tasks'=>$tasks));

//

Web服务生成以下输出:

{"tasks":[{"row":{"userid":"1","task":"send email to Bob","longtask":"include attached memo"}}]}

但是,我在阅读IOS时遇到了很多麻烦,这表明Web服务可能有更好的格式.

结构不同于我在教程中找到的用于将json读入IOS的其他资源(其中没有一个使用php / mysql).

任何人都可以告诉我一个更好的方法来构建json或者代码来读取iOS中的这个json以获取用户ID,任务和其他变量.

当我尝试这个时,我得到一个错误,它不能在index:0处的rad行

NSError* error;

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1

options:kNilOptions

error:&error];

NSLog(@"about to print json: %@",json);

NSMutableArray *getElement = [json objectForKey:@"tasks"];

for (NSDictionary *dict in getElement) {

NSArray *array = [dict objectForKey:@"row"];

NSString *str = [array objectAtIndex:0];

}

在此先感谢您的任何建议.

解决方法:

方法1:编辑PHP代码

索引0不可用,因为您使用mysql_fetch_assoc从PHP获取关联数组.

默认情况下,使用mysql_fetch_array将返回一个包含从零开始的索引和关联键的数组.

$sql = "SELECT userid,task,longtask FROM tasks WHERE userid = 1 LIMIT 1";

$res = mysql_query($sql) or die(mysql_error());

$tasks = array();

while($row = mysql_fetch_array($res)) {

$tasks[] = array('row'=>$row);

}

echo json_encode(array('tasks'=>$tasks));

会输出

{"tasks":[{"row":{"0":"1","userid":"1","1":"send email to Bob","task":"send email to Bob","2":"include attached memo","longtask":"include attached memo"}}]}

现在,您可以使用键0或userid检索用户标识.

方法2:编辑iOS代码

编辑iOS代码.但要实现这一点,您必须知道行中的键.

NSString *str = [array objectForKey:@"userid"];`

标签:json,php,mysql,ios

来源: https://codeday.me/bug/20190708/1399895.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值